Add /set-cursor URI
[phoros.git] / fasttrack.lisp
blobc0a9141829145b0f81737e3b89617909a0227d8a
1 ;;; PHOROS -- Photogrammetric Road Survey
2 ;;; Copyright (C) 2012, 2016 Bert Burgemeister
3 ;;;
4 ;;; This program is free software; you can redistribute it and/or modify
5 ;;; it under the terms of the GNU General Public License as published by
6 ;;; the Free Software Foundation; either version 2 of the License, or
7 ;;; (at your option) any later version.
8 ;;;
9 ;;; This program is distributed in the hope that it will be useful,
10 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 ;;; GNU General Public License for more details.
13 ;;;
14 ;;; You should have received a copy of the GNU General Public License along
15 ;;; with this program; if not, write to the Free Software Foundation, Inc.,
16 ;;; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 (in-package #:phoros-fasttrack)
21 ;;; Debug helpers. TODO: remove them.
22 (defparameter *t* nil)
23 (defparameter *tt* nil)
25 (cffi:define-foreign-library phoml
26 (:unix (:or "./libphoml.so"
27 "./phoml/lib/libphoml.so"))
28 (t (:default "libphoml")))
30 (setf *read-default-float-format* 'double-float)
32 (defparameter *photogrammetry-mutex* (bt:make-lock "photogrammetry"))
34 (defparameter *fasttrack-version*
35 (asdf:component-version (asdf:find-system :phoros))
36 "Fasttrack version as defined in system definition. TODO: enforce equality with *phoros-version*")
38 (defstruct (db-credentials (:type list)) database user password host (port-key :port :read-only t) (port 5432) (ssl-key :use-ssl :read-only t) (ssl :no) (modifiedp-key :modifiedp :read-only t) (modifiedp t) (table-key :table :read-only t) table (allow-other-keys-key :allow-other-keys :read-only t) (allow-other-keys-value t :read-only t))
40 (defvar *postgresql-road-network-credentials* (make-db-credentials)
41 "A list: (database user password host :port 5432 :use-ssl ssl-p.")
43 (defvar *postgresql-zeb-credentials* (make-db-credentials)
44 "A list: (database user password host :port 5432 use-ssl :ssl-p.")
46 (defvar *road-network-chart-configuration* nil
47 "Database columns selected for rendering.")
49 (defvar *zeb-chart-configuration* nil
50 "Database columns selected for rendering.")
52 (defvar *accidents-chart-configuration* (list nil nil nil)
53 "Accidents rendering parameters.")
55 (defvar *postgresql-accidents-credentials* (make-db-credentials)
56 "A list: (database user password host &key (port 5432) use-ssl).")
58 (defvar *road-section* nil
59 "If there is a chart, we store a list of its parameters (table vnk
60 nnk road-section-length) here.")
62 (defvar *road-section-raw-data* (make-hash-table :size 97)
63 "Undigested selected row numbers from road section dialog")
65 (defvar *road-section-selection* '()
66 "Row numbers of the road sections selected for processing.")
68 (defvar *road-network-chart-raw-data* (make-hash-table :size 997 :test #'equal)
69 "Raw messages from the road network part of the chart dialog")
71 (defvar *accidents-chart-raw-data* (list nil nil nil)
72 "Undigested input from the accidents part of the chart dialog.")
74 (defvar *zeb-chart-raw-data* (make-hash-table :size 997 :test #'equal)
75 "Raw messages from road section dialog")
77 (defparameter *aggregate-view-columns*
78 (list 'usable
79 'recorded-device-id ;debug
80 'device-stage-of-life-id ;debug
81 'generic-device-id ;debug
82 'directory
83 'measurement-id
84 'filename 'byte-position 'point-id
85 'trigger-time
86 ;;'coordinates ;the search target
87 'longitude 'latitude 'ellipsoid-height
88 'cartesian-system
89 'east-sd 'north-sd 'height-sd
90 'roll 'pitch 'heading
91 'roll-sd 'pitch-sd 'heading-sd
92 'sensor-width-pix 'sensor-height-pix
93 'pix-size
94 'bayer-pattern 'color-raiser
95 'mounting-angle
96 'dx 'dy 'dz 'omega 'phi 'kappa
97 'c 'xh 'yh 'a1 'a2 'a3 'b1 'b2 'c1 'c2 'r0
98 'b-dx 'b-dy 'b-dz 'b-rotx 'b-roty 'b-rotz
99 'b-ddx 'b-ddy 'b-ddz
100 'b-drotx 'b-droty 'b-drotz)
101 "Most of the column names of aggregate-view.")
103 (defvar *phoros-cookies* nil
104 "Container for cookies sent by Phoros server")
106 (defvar *phoros-url* nil
107 "URL of the Phoros project currently in use.")
109 (defvar *phoros-credentials* '("user" "password")
110 "List of (user password) used for login at *phoros-url*.")
112 (defvar *cache-dir* '(:absolute "home" "bertb" "phoros" "cache"))
113 ;; TODO: invent cache validity checks
115 (defparameter *image-size* '(800 750)
116 "Image size in pixels in a list (width height).")
118 (defparameter *chart-height* 200
119 "Height of chart in pixels.")
121 (defparameter *chart-fringe* 20
122 "Lower, uncharted part of chart.")
124 (defparameter *chart-tail* 200
125 "Rightmost, uncharted part of chart.")
127 (defparameter *scale-distance* 40
128 "Horizontal distance between two scales.")
130 (defvar *rear-view-image-path* ""
131 "Filename of the currently displayed image.")
133 (defvar *front-view-image-path* ""
134 "Filename of the currently displayed image.")
136 (defvar *jump-to-station-thread* nil)
138 (defvar *cruise-control-thread* nil)
140 (defvar *front-view-image-thread* nil
141 "The thread that is currently downloading the image.")
143 (defvar *rear-view-image-thread* nil
144 "The thread that is currently downloading the image.")
146 (defvar *show-rear-view-p* t)
148 (defvar *show-front-view-p* t)
150 (defparameter *cursor-color* "orange"
151 "Color of cursor in both chart and images.")
153 (defparameter *big-step* 10
154 "Station increment/decrement.")
156 (defparameter *pipeglade-out-lock* (bt:make-lock))
157 (defparameter *pipeglade-out-fifo* "in.fifo")
158 (defparameter *pipeglade-in-fifo* "out.fifo")
160 (defun pipeglade-out (widget action &rest data)
161 "Send a pipeglade command to UI."
162 (bt:with-lock-held (*pipeglade-out-lock*)
163 (with-open-file (out *pipeglade-out-fifo*
164 :direction :output
165 :if-exists :append
166 :if-does-not-exist :error)
167 (format out "~A:~A~{ ~A~}~%" widget action data))))
170 (defun ensure-hyphen-before-digit (symbol)
171 "Return symbol with hyphens inserted after each letter that is
172 followed by a digit. "
173 (intern
174 (coerce
175 (loop
176 with need-hyphen-before-next-digit-p
177 for c across (string symbol)
178 if (and need-hyphen-before-next-digit-p (digit-char-p c))
179 collect #\- and collect c and do (setf need-hyphen-before-next-digit-p nil)
180 else collect c and do (setf need-hyphen-before-next-digit-p nil)
182 if (alpha-char-p c) do (setf need-hyphen-before-next-digit-p t) end)
183 'string)))
186 (defmacro with-statusbar-message (message &body body)
187 "Push message to statusbar while body is executing."
188 `(unwind-protect
189 (progn
190 (pipeglade-out "statusbar" "push_id" (sxhash ,message) ,message)
191 ,@body)
192 (pipeglade-out "statusbar" "pop_id" (sxhash ,message))))
194 (defmacro with-spinner (spinner &body body)
195 "Let spinner spin while body is executing."
196 `(unwind-protect
197 (progn
198 (pipeglade-out ,spinner "start")
199 ,@body)
200 (pipeglade-out ,spinner "stop")))
204 (defmacro defun-cached (name (&rest args) &body body &aux (doc ""))
205 "Define a function whose return value must be readibly printable, is
206 being read from a chache if possible, and is being cached if
207 necessary. The function defined has a secondary return value
208 cached-p. If function is called with :from-cache-only t, let it
209 return nil and nil if there is nothing cached."
210 (when (stringp (car body))
211 (setf doc (car body))
212 (setf body (cdr body)))
213 (cl-utilities:with-unique-names (input-stream output-stream)
214 `(defun ,name (,@args &key from-cache-only)
215 ,doc
216 (ensure-directories-exist (cache-file-name ',name ,@args))
217 (with-open-file (,input-stream (cache-file-name ',name ,@args)
218 :direction :input
219 :if-does-not-exist nil)
220 (if ,input-stream
221 (values (read ,input-stream) t)
222 (values (unless from-cache-only
223 (with-statusbar-message (format nil "populataing cache (~A)" ',name)
224 (with-open-file (,output-stream (cache-file-name ',name ,@args)
225 :direction :output)
226 (prin1 (progn ,@body)
227 ,output-stream))))
228 nil))))))
230 (eval '(defstruct coordinates
231 longitude
232 latitude
233 ellipsoid-height
234 azimuth))
236 (eval `(defstruct image-data
237 ;; fasttrack auxiliary slots
238 station
239 station-coordinates
240 (rear-view-p nil)
241 ;; original Phoros image data slots
242 ,@(mapcar #'ensure-hyphen-before-digit *aggregate-view-columns*)))
244 (defun main ()
245 (in-package #:phoros-fasttrack) ;for reading of cached #S(...) forms
246 (cffi:use-foreign-library phoml)
247 (trivial-shell:shell-command "../pipeglade/pipeglade -i in.fifo -o out.fifo -u fasttrack.ui -b -l log.log")
248 (loop until (and (probe-file "in.fifo") (probe-file "out.fifo")))
249 (pipeglade-out "main" "set_title" "Phoros Fasttrack")
250 (pipeglade-out "credentials" "set_title" "Phoros Fasttrack - Credentials")
251 (pipeglade-out "road_section" "set_title" "Phoros Fasttrack - Choose Road Section")
252 (pipeglade-out "chart_configuration" "set_title" "Phoros Fasttrack - Chart Configuration")
253 (restore-road-network-credentials)
254 (restore-zeb-credentials)
255 (restore-accidents-credentials)
256 (restore-phoros-credentials)
257 (restore-road-network-chart-configuration)
258 (restore-zeb-chart-configuration)
259 (restore-accidents-chart-configuration)
260 (restore-road-section)
261 (update-credentials-dialog)
262 (check-credentials-dialog-statuses)
263 (ignore-errors (apply #'phoros-login *phoros-url* *phoros-credentials*))
264 ;; Kludge: tickle the dialog to make spinbuttons receptive
265 (pipeglade-out "chart_configuration" "set_visible" 1)
266 (pipeglade-out "chart_configuration" "set_visible" 0)
267 (pipeglade-out "chart_road_network" "set_line_cap" 1 "round")
268 (pipeglade-out "chart_road_network" "set_line_join" 1 "round")
269 (pipeglade-out "chart_zeb" "set_line_cap" 1 "round")
270 (pipeglade-out "chart_zeb" "set_line_join" 1 "round")
271 (pipeglade-out "chart_accidents" "set_line_join" 1 "miter")
272 (pipeglade-out "chart_accidents" "set_line_width" 1 1)
273 (pipeglade-out "chart_cursor" "set_source_rgba" 1 *cursor-color*)
274 (pipeglade-out "chart_cursor" "set_line_width" 1 3)
275 (pipeglade-out "chart_cursor" "set_dash" 1 3)
276 (pipeglade-out "chart_cursor" "set_font_size" 1 10)
277 (pipeglade-out "chart_road_network_scale" "set_font_size" 1 10)
278 (pipeglade-out "zeb_network_scale" "set_font_size" 1 10)
279 (pipeglade-out "draw_rearview" "set_source_rgba" 1 *cursor-color*)
280 (pipeglade-out "draw_rearview" "set_line_cap" 1 "round")
281 (pipeglade-out "draw_rearview" "set_line_width" 1 2)
282 (pipeglade-out "draw_rearview" "set_font_size" 1 10)
283 (pipeglade-out "draw_frontview" "set_source_rgba" 1 *cursor-color*)
284 (pipeglade-out "draw_frontview" "set_line_cap" 1 "round")
285 (pipeglade-out "draw_frontview" "set_line_width" 1 2)
286 (pipeglade-out "draw_frontview" "set_font_size" 1 10)
287 (with-open-file (in *pipeglade-in-fifo*
288 :direction :input
289 :if-does-not-exist :error)
290 ;; getting rid of initial feedback from credentials dialog:
291 (with-statusbar-message "please wait" (sleep 1))
292 (clear-input in)
293 (populate-road-section-dialog)
294 (restore-road-section-image-counts)
295 (restore-road-section-selection)
296 (update-road-section-selection)
297 (set-road-section)
298 (update-station (saved-station))
299 (populate-chart-dialog)
300 (refresh-chart)
301 (loop
302 for message = (read-line in nil)
304 (cond
305 ((message-name= "quit" message)
306 (pipeglade-out "_" "main_quit")
307 (loop-finish))
308 ((message-name= "station_scale" message)
309 (jump-to-station (parse-integer (message-data message) :junk-allowed t)))
310 ((message-name= "show_road_network_chart" message)
311 (pipeglade-out "chart_road_network" "set_visible" (message-info message))
312 (pipeglade-out "chart_road_network_scale" "set_visible" (message-info message)))
313 ((message-name= "show_zeb_chart" message)
314 (pipeglade-out "chart_zeb" "set_visible" (message-info message))
315 (pipeglade-out "chart_zeb_scale" "set_visible" (message-info message)))
316 ((message-name= "show_accidents_chart" message)
317 (pipeglade-out "chart_accidents" "set_visible" (message-info message)))
318 ((message-name= "show_rear_view" message)
319 (setf *show-rear-view-p* (string= (message-info message) "1")))
320 ((message-name= "show_front_view" message)
321 (setf *show-front-view-p* (string= (message-info message) "1")))
322 ((message-name= "big_step" message)
323 (let* ((step (parse-integer (message-data message) :junk-allowed t))
324 (label-text (format nil "~D m" step)))
325 (pipeglade-out "back" "set_label" label-text)
326 (pipeglade-out "forward" "set_label" label-text)
327 (pipeglade-out "big_step_back" "set_label" label-text)
328 (pipeglade-out "big_step_forward" "set_label" label-text)
329 (pipeglade-out "station_scale" "set_increments" 1 step)
330 (setf *big-step* step)))
331 ((message-name= "step_back" message)
332 (stop-cruise-control)
333 (pipeglade-out "station_scale" "set_value" (1- (saved-station))))
334 ((message-name= "step_forward" message)
335 (stop-cruise-control)
336 (pipeglade-out "station_scale" "set_value" (1+ (saved-station))))
337 ((message-name= "big_step_back" message)
338 (stop-cruise-control)
339 (pipeglade-out "station_scale" "set_value" (- (saved-station) *big-step*)))
340 ((message-name= "big_step_forward" message)
341 (stop-cruise-control)
342 (pipeglade-out "station_scale" "set_value" (+ (saved-station) *big-step*)))
343 ((message-name= "back" message)
344 (stop-cruise-control)
345 (cruise-control :backwardp t))
346 ((message-name= "forward" message)
347 (stop-cruise-control)
348 (cruise-control :backwardp nil))
349 ((message-name= "stop" message)
350 (stop-cruise-control))
351 ((message-name= "first_section" message)
352 (set-road-section)
353 (refresh-chart)
354 (pipeglade-out "station_scale" "set_value" 1)
355 (pipeglade-out "station_scale" "set_value" 0))
356 ((message-name= "previous_section" message)
357 (set-road-section :direction :predecessor)
358 (refresh-chart)
359 (pipeglade-out "station_scale" "set_value" 1)
360 (pipeglade-out "station_scale" "set_value" 0))
361 ((message-name= "next_section" message)
362 (set-road-section :direction :successor)
363 (refresh-chart)
364 (pipeglade-out "station_scale" "set_value" 1)
365 (pipeglade-out "station_scale" "set_value" 0))
366 ((message-name= "last_section" message)
367 (set-road-section :direction :last)
368 (refresh-chart)
369 (pipeglade-out "station_scale" "set_value" 1)
370 (pipeglade-out "station_scale" "set_value" 0))
371 ((message-name= "road_sections" message)
372 (collect-road-section-select message))
373 ((message-name= "road_section_ok" message)
374 (digest-road-section-raw-data))
375 ((message-name= "road_section_cncl" message)
376 (restore-road-section-selection)
377 (pipeglade-out "road_section" "set_visible" 0))
378 ((message-name= "road_network" message)
379 (collect-raw-message message *road-network-chart-raw-data*))
380 ((message-name= "zeb" message)
381 (collect-raw-message message *zeb-chart-raw-data*))
382 ((message-name= "render_accidents" message)
383 (setf (first *accidents-chart-raw-data*) (message-info message)))
384 ((message-name= "accidents_from" message)
385 (setf (second *accidents-chart-raw-data*) (message-data message)))
386 ((message-name= "accidents_to" message)
387 (setf (third *accidents-chart-raw-data*) (message-data message)))
388 ((message-name= "chart_configuration_ok" message)
389 (setf *road-network-chart-configuration* (digest-chart-raw-data *road-network-chart-raw-data*))
390 (save-place *road-network-chart-configuration* 'road-network-chart-configuration)
391 (setf *zeb-chart-configuration* (digest-chart-raw-data *zeb-chart-raw-data*))
392 (save-place *zeb-chart-configuration* 'zeb-chart-configuration)
393 (digest-accidents-chart-raw-data)
394 (update-accidents-chart-dialog)
395 (pipeglade-out "text_values" "clear")
396 (refresh-chart))
397 ((message-name= "chart_configuration_cncl" message)
398 (update-accidents-chart-dialog)
399 (setf *accidents-chart-raw-data* (list nil nil nil))
400 (pipeglade-out "chart_configuration" "set_visible" 0))
401 ((message-name= "credentials_check" message)
402 (check-credentials-dialog-statuses))
403 ((message-name= "credentials_ok" message)
404 (check-credentials-dialog-statuses)
405 (when (db-credentials-modifiedp *postgresql-road-network-credentials*)
406 (invalidate-road-section-selection)
407 (invalidate-road-section)
408 (invalidate-road-network-chart-configuration)
409 (populate-road-section-dialog)
410 (update-chart-dialog)
411 (save-road-network-credentials nil))
412 (when (db-credentials-modifiedp *postgresql-zeb-credentials*)
413 (update-chart-dialog)
414 (invalidate-zeb-chart-configuration)
415 (pipeglade-out "text_values" "clear")
416 (refresh-chart)
417 (save-zeb-credentials nil))
418 (when (db-credentials-modifiedp *postgresql-accidents-credentials*)
419 (refresh-chart)
420 (save-accidents-credentials nil))
421 (ignore-errors (apply #'phoros-login *phoros-url* *phoros-credentials*))
422 (forget-images-being-launched)
423 (jump-to-station (saved-station))
424 (update-chart-dialog))
425 ((message-name= "road_network_host" message)
426 (setf (db-credentials-host *postgresql-road-network-credentials*) (message-data message))
427 (save-road-network-credentials t))
428 ((message-name= "road_network_port" message)
429 (setf (db-credentials-port *postgresql-road-network-credentials*) (parse-integer (message-data message)))
430 (save-road-network-credentials t))
431 ((message-name= "road_network_ssl" message)
432 (setf (db-credentials-ssl *postgresql-road-network-credentials*) (message-data message))
433 (save-road-network-credentials t))
434 ((message-name= "road_network_database" message)
435 (setf (db-credentials-database *postgresql-road-network-credentials*) (message-data message))
436 (save-road-network-credentials t))
437 ((message-name= "road_network_user" message)
438 (setf (db-credentials-user *postgresql-road-network-credentials*) (message-data message))
439 (save-road-network-credentials t))
440 ((message-name= "road_network_password" message)
441 (setf (db-credentials-password *postgresql-road-network-credentials*) (message-data message))
442 (save-road-network-credentials t))
443 ((message-name= "road_network_table" message)
444 (setf (db-credentials-table *postgresql-road-network-credentials*) (message-data message))
445 (save-road-network-credentials t))
446 ((message-name= "zeb_host" message)
447 (setf (db-credentials-host *postgresql-zeb-credentials*) (message-data message))
448 (save-zeb-credentials t))
449 ((message-name= "zeb_port" message)
450 (setf (db-credentials-port *postgresql-zeb-credentials*) (parse-integer (message-data message)))
451 (save-zeb-credentials t))
452 ((message-name= "zeb_ssl" message)
453 (setf (db-credentials-ssl *postgresql-zeb-credentials*) (message-data message))
454 (save-zeb-credentials t))
455 ((message-name= "zeb_database" message)
456 (setf (db-credentials-database *postgresql-zeb-credentials*) (message-data message))
457 (save-zeb-credentials t))
458 ((message-name= "zeb_user" message)
459 (setf (db-credentials-user *postgresql-zeb-credentials*) (message-data message))
460 (save-zeb-credentials t))
461 ((message-name= "zeb_password" message)
462 (setf (db-credentials-password *postgresql-zeb-credentials*) (message-data message))
463 (save-zeb-credentials t))
464 ((message-name= "zeb_table" message)
465 (setf (db-credentials-table *postgresql-zeb-credentials*) (message-data message))
466 (save-zeb-credentials t))
467 ((message-name= "accidents_host" message)
468 (setf (db-credentials-host *postgresql-accidents-credentials*) (message-data message))
469 (save-accidents-credentials t))
470 ((message-name= "accidents_port" message)
471 (setf (db-credentials-port *postgresql-accidents-credentials*) (parse-integer (message-data message)))
472 (save-accidents-credentials t))
473 ((message-name= "accidents_ssl" message)
474 (setf (db-credentials-ssl *postgresql-accidents-credentials*) (message-data message))
475 (save-accidents-credentials t))
476 ((message-name= "accidents_database" message)
477 (setf (db-credentials-database *postgresql-accidents-credentials*) (message-data message))
478 (save-accidents-credentials t))
479 ((message-name= "accidents_user" message)
480 (setf (db-credentials-user *postgresql-accidents-credentials*) (message-data message))
481 (save-accidents-credentials t))
482 ((message-name= "accidents_password" message)
483 (setf (db-credentials-password *postgresql-accidents-credentials*) (message-data message))
484 (save-accidents-credentials t))
485 ((message-name= "accidents_table" message)
486 (setf (db-credentials-table *postgresql-accidents-credentials*) (message-data message))
487 (save-accidents-credentials t))
488 ((message-name= "phoros_url" message)
489 (setf *phoros-url* (message-data message))
490 (save-phoros-credentials))
491 ((message-name= "phoros_user" message)
492 (setf (first *phoros-credentials*) (message-data message))
493 (save-phoros-credentials))
494 ((message-name= "phoros_password" message)
495 (setf (second *phoros-credentials*) (message-data message))
496 (save-phoros-credentials))
498 (print (list "fallen through:" message)))))))
500 (defun invalidate-road-section ()
501 (setf *road-section* nil)
502 (save-road-section))
504 (defun invalidate-road-section-selection ()
505 (setf *road-section-selection* '())
506 (save-road-section-selection))
508 (defun invalidate-road-network-chart-configuration ()
509 (setf *road-network-chart-configuration* nil)
510 (save-place *road-network-chart-configuration* 'road-network-chart-configuration))
512 (defun invalidate-zeb-chart-configuration ()
513 (setf *zeb-chart-configuration* nil)
514 (save-place *zeb-chart-configuration* 'zeb-chart-configuration))
516 (defun message-name= (string message)
517 (let ((colon-position (position #\: message)))
518 (string= string (subseq message 0 colon-position))))
520 (defun message-info (message)
521 (let ((colon-position (position #\: message))
522 (space-position (position #\Space message)))
523 (subseq message (1+ colon-position) space-position)))
525 (defun message-data (message)
526 (let ((space-position (position #\Space message)))
527 (when space-position
528 (subseq message (1+ space-position)))))
530 (defun message-data-list (message)
531 (cl-utilities:split-sequence #\Space (message-data message)))
533 (defun collect-road-section-select (message)
534 (let ((data (message-data-list message)))
535 (if (string= (second data) "4") ;"select" column
536 (setf (gethash (parse-integer (first data)) ;row number
537 *road-section-raw-data*)
538 (string= (third data) "1")))))
540 (defun collect-accidents-message-data (&key (renderp 0 renderp-p) (from nil from-p) (to nil to-p) (ok-pressed nil ok-pressed-p))
541 (when renderp-p (setf (first *accidents-chart-raw-data*) renderp))
542 (when from-p (setf (second *accidents-chart-raw-data*) (parse-integer from :junk-allowed t)))
543 (when to-p (setf (third *accidents-chart-raw-data*) (parse-integer to :junk-allowed t))))
545 (defun collect-raw-message (message place)
546 (unless (string= (message-info message) "clicked")
547 (let ((data (message-data-list message)))
548 (setf (gethash (list (parse-integer (first data)) ;row number
549 (parse-integer (second data))) ;column number
550 place)
551 (third data)))))
553 (defun digest-road-section-raw-data ()
554 (let ((sections (sections (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))))
555 (maphash (lambda (key value)
556 (if value
557 (pushnew key *road-section-selection*)
558 (setf *road-section-selection* (remove key *road-section-selection*))))
559 *road-section-raw-data*)
560 (setf *road-section-selection* (sort *road-section-selection* #'<))
561 (save-road-section-selection)
562 (set-road-section)
563 (save-road-section)
565 (when (update-station) ;new section
566 (restore-road-section-image-counts)
567 (prepare-chart))
568 (clrhash *road-section-raw-data*)))
570 (defstruct (data-style (:type list)) chartp drawablep textp name color width dash)
572 (defun clear-main-window ()
573 (dolist (drawingarea '("chart_accidents" "chart_road_network" "chart_zeb" "chart_cursor" "chart_road_network_scale" "chart_zeb_scale" "draw_rearview" "draw_frontview"))
574 (pipeglade-out drawingarea "remove" 2))
575 (dolist (image '("img_rearview" "img_frontview"))
576 (pipeglade-out image "set_from_file"))
577 (pipeglade-out "text_values" "clear"))
579 (defun digest-chart-raw-data (raw-data)
580 "Return the information read from raw-data in chart configuration format."
581 (let* ((row-count
582 (loop
583 for (row column) being each hash-key of raw-data
584 when (zerop column) ;arbitrary column representing its row
585 count it))
586 (chart-configuration
587 (make-array (list row-count))))
588 (loop
589 for i from 0 below row-count
591 (setf (svref chart-configuration i)
592 (make-data-style)))
593 (loop
594 for (row column) being each hash-key of raw-data using (hash-value value)
596 (case column
597 (0 ;column name
598 (setf (data-style-name (svref chart-configuration row)) value))
599 ;; 1 would be type
600 (2 ;width
601 (setf (data-style-width (svref chart-configuration row)) value))
602 (3 ;color
603 (setf (data-style-color (svref chart-configuration row)) value))
604 (4 ;dash
605 (setf (data-style-dash (svref chart-configuration row)) value))
606 (5 ;selected
607 (setf (data-style-chartp (svref chart-configuration row)) (string= value "1")))
609 (setf (data-style-textp (svref chart-configuration row)) (string= value "1")))
611 (setf (data-style-drawablep (svref chart-configuration row)) (string= value "1")))))
612 chart-configuration))
614 (defun digest-accidents-chart-raw-data ()
615 (setf *accidents-chart-configuration*
616 (mapcar (lambda (configuration-value raw-value)
617 (or (format nil "~D" (parse-integer raw-value :junk-allowed t)) configuration-value))
618 *accidents-chart-configuration*
619 *accidents-chart-raw-data*))
620 (save-accidents-chart-configuration))
622 (defun road-network-chart-data (column vnk nnk chart-height)
623 "Return a list of lists of station and column values between vnk
624 and nnk scaled into chart-height; the minimum column value; and the
625 maximum column value. Both minimum and maximum are nil if data is
626 constant."
627 (let ((table (intern (db-credentials-table *postgresql-road-network-credentials*))))
628 (with-connection *postgresql-road-network-credentials*
629 (setf column (intern (string-upcase column)))
630 (destructuring-bind (minimum maximum)
631 (query (:select (:type (:min column) real)
632 (:type (:max column) real)
633 :from table
634 :where (:and (:= 'vnk vnk)
635 (:= 'nnk nnk)))
636 :list)
637 (if (and (numberp minimum) (numberp maximum))
638 (let* ((span (- maximum minimum))
639 (m (if (zerop span)
641 (/ chart-height span)))
642 (b (if (zerop span)
643 (* chart-height 1/2)
644 (+ chart-height (* m minimum)))))
645 (values
646 (query (:order-by
647 (:select 'nk-station
648 (:- b (:* m (:type column real)))
649 :from table
650 :where (:and (:= 'vnk vnk)
651 (:= 'nnk nnk)))
652 'nk-station))
653 ;; (unless (zerop span) minimum)
654 ;; (unless (zerop span) maximum)
655 minimum
656 maximum
658 (values nil nil nil))))))
660 (defun zeb-chart-data (column vnk nnk chart-height)
661 "Return a list of lists of station and column values between vnk
662 and nnk scaled into chart-height; the minimum column value; and the
663 maximum column value. Both minimum and maximum are nil if data is
664 constant."
665 (let ((table (intern (db-credentials-table *postgresql-zeb-credentials*))))
666 (with-connection *postgresql-zeb-credentials*
667 (setf column (intern (string-upcase column)))
668 (destructuring-bind (minimum maximum)
669 (query (:select (:type (:min column) real)
670 (:type (:max column) real)
671 :from table
672 :where (:and (:= 'vnk vnk)
673 (:= 'nnk nnk)))
674 :list)
675 (if (and (numberp minimum) (numberp maximum))
676 (let* ((span (- maximum minimum))
677 (m (if (zerop span)
679 (/ chart-height span)))
680 (b (if (zerop span)
681 (* chart-height 1/2)
682 (+ chart-height (* m minimum)))))
683 (values
684 (query (:order-by
685 (:select 'vst
686 (:- b (:* m (:type column real)))
687 'bst
688 (:- b (:* m (:type column real)))
689 :from table
690 :where (:and (:= 'vnk vnk)
691 (:= 'nnk nnk)))
692 'vst))
693 ;; (unless (zerop span) minimum)
694 ;; (unless (zerop span) maximum)
695 minimum
696 maximum
698 (values nil nil nil))))))
702 (defun road-network-text-value (column vnk nnk station)
703 "Return column value at station between vnk and nnk."
704 (let ((table (intern (db-credentials-table *postgresql-road-network-credentials*))))
705 (with-connection *postgresql-road-network-credentials*
706 (setf column (intern (string-upcase column)))
707 (ignore-errors
708 (query (:select column
709 :from table
710 :where (:and (:= 'vnk vnk)
711 (:= 'nnk nnk)
712 (:= 'nk_station station)))
713 :single)))))
715 (defun zeb-text-value (column vnk nnk station)
716 "Return column value at station between vnk and nnk."
717 (let ((table (intern (db-credentials-table *postgresql-zeb-credentials*))))
718 (with-connection *postgresql-zeb-credentials*
719 (setf column (intern (string-upcase column)))
720 (ignore-errors
721 (query (:select column
722 :from table
723 :where (:and (:= 'vnk vnk)
724 (:= 'nnk nnk)
725 (:between station 'vst 'bst)))
726 :single)))))
728 (defun show-text (row-number station text-data-function column vnk nnk color width dash)
729 (let ((value (funcall text-data-function column vnk nnk station)))
730 (pipeglade-out "text_values" "set" row-number 0 column)
731 (pipeglade-out "text_values" "set" row-number 1 value)
732 (pipeglade-out "text_values" "set" row-number 2 color)
733 (pipeglade-out "text_values" "set" row-number 3 (* 4 (parse-integer width :junk-allowed t))))) ;text size
735 (defun put-text-values (vnk nnk station)
736 (let ((row-number 0))
737 (when (vectorp *road-network-chart-configuration*)
738 (loop
739 for style-definition across *road-network-chart-configuration*
741 (when (data-style-textp style-definition)
742 (show-text row-number station #'road-network-text-value (data-style-name style-definition) vnk nnk (data-style-color style-definition) (data-style-width style-definition) (data-style-dash style-definition))
743 (incf row-number))))
744 (when (vectorp *zeb-chart-configuration*)
745 (loop
746 for style-definition across *zeb-chart-configuration*
748 (when (data-style-textp style-definition)
749 (show-text row-number station #'zeb-text-value (data-style-name style-definition) vnk nnk (data-style-color style-definition) (data-style-width style-definition) (data-style-dash style-definition))
750 (incf row-number))))))
752 (defun accidents-data (vnk nnk &key
753 (year-min most-negative-fixnum)
754 (year-max most-positive-fixnum))
755 "Return a list of plists containing accident data for the road
756 section between vnk and nnk."
757 (let ((table (intern (db-credentials-table *postgresql-accidents-credentials*))))
758 (with-connection *postgresql-accidents-credentials*
759 (query (:order-by
760 (:select 'nk-station 'fahrtrichtung 'unfalltyp 'unfallkategorie 'alkohol
761 :from table
762 :where (:and (:= 'vnk vnk)
763 (:= 'nnk nnk)
764 (:between 'jahr year-min year-max)))
765 'nk-station 'jahr 'monat 'tag 'stunde 'minuten)
766 :plists))))
768 (defun populate-road-section-dialog ()
769 (with-statusbar-message "populating road section list"
770 (with-spinner "road_section_spinner"
771 (pipeglade-out "road_sections" "clear")
772 (ignore-errors
773 (with-connection *postgresql-road-network-credentials*
774 (let ((sections (sections (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))))
775 (loop
776 for (vnk nnk length) in sections
777 for row-number from 0
779 (add-vnk-nnk-leaf vnk nnk length row-number))))))))
781 (defun update-credentials-dialog ()
782 (with-statusbar-message "initialising credentials"
783 (pipeglade-out "road_network_host" "set_text" (db-credentials-host *postgresql-road-network-credentials*))
784 (pipeglade-out "road_network_port" "set_text" (db-credentials-port *postgresql-road-network-credentials*))
785 (pipeglade-out "road_network_ssl" "set_active" (if (eq (db-credentials-ssl *postgresql-road-network-credentials*) :no) 0 1))
786 (pipeglade-out "road_network_database" "set_text" (db-credentials-database *postgresql-road-network-credentials*))
787 (pipeglade-out "road_network_table" "set_text" (db-credentials-table *postgresql-road-network-credentials*))
788 (pipeglade-out "road_network_user" "set_text" (db-credentials-user *postgresql-road-network-credentials*))
789 (pipeglade-out "road_network_password" "set_text" (db-credentials-password *postgresql-road-network-credentials*))
790 (pipeglade-out "road_network_status" "set_text" "?")
791 (pipeglade-out "zeb_host" "set_text" (db-credentials-host *postgresql-zeb-credentials*))
792 (pipeglade-out "zeb_port" "set_text" (db-credentials-port *postgresql-zeb-credentials*))
793 (pipeglade-out "zeb_ssl" "set_active" (if (eq (db-credentials-ssl *postgresql-zeb-credentials*) :no) 0 1))
794 (pipeglade-out "zeb_database" "set_text" (db-credentials-database *postgresql-zeb-credentials*))
795 (pipeglade-out "zeb_table" "set_text" (db-credentials-table *postgresql-zeb-credentials*))
796 (pipeglade-out "zeb_user" "set_text" (db-credentials-user *postgresql-zeb-credentials*))
797 (pipeglade-out "zeb_password" "set_text" (db-credentials-password *postgresql-zeb-credentials*))
798 (pipeglade-out "zeb_status" "set_text" "?")
799 (pipeglade-out "accidents_host" "set_text" (db-credentials-host *postgresql-accidents-credentials*))
800 (pipeglade-out "accidents_port" "set_text" (db-credentials-port *postgresql-accidents-credentials*))
801 (pipeglade-out "accidents_ssl" "set_active" (if (eq (db-credentials-ssl *postgresql-accidents-credentials*) :no) 0 1))
802 (pipeglade-out "accidents_database" "set_text" (db-credentials-database *postgresql-accidents-credentials*))
803 (pipeglade-out "accidents_table" "set_text" (db-credentials-table *postgresql-accidents-credentials*))
804 (pipeglade-out "accidents_user" "set_text" (db-credentials-user *postgresql-accidents-credentials*))
805 (pipeglade-out "accidents_password" "set_text" (db-credentials-password *postgresql-accidents-credentials*))
806 (pipeglade-out "accidents_status" "set_text" "?")
807 (destructuring-bind (user password) *phoros-credentials*
808 (pipeglade-out "phoros_url" "set_text" *phoros-url*)
809 (pipeglade-out "phoros_user" "set_text" user)
810 (pipeglade-out "phoros_password" "set_text" password)
811 (pipeglade-out "phoros_status" "set_text" "?"))))
813 (defun check-credentials-dialog-statuses ()
814 (with-statusbar-message "checking road network db connection"
815 (pipeglade-out "road_network_status" "set_text" (check-db *postgresql-road-network-credentials*)))
816 (with-statusbar-message "checking zeb db connection"
817 (pipeglade-out "zeb_status" "set_text" (check-db *postgresql-zeb-credentials*)))
818 (with-statusbar-message "checking accidents db connection"
819 (pipeglade-out "accidents_status" "set_text" (check-db *postgresql-accidents-credentials*)))
820 (with-statusbar-message "checking Phoros connection"
821 (pipeglade-out "phoros_status" "set_text" (apply #'check-phoros *phoros-url* *phoros-credentials*))))
823 (defun save-place (place filename-stump)
824 "Save place into a file whose name is based on symbol filename-stump."
825 (let ((cache-file-name (cache-file-name filename-stump)))
826 (ensure-directories-exist cache-file-name)
827 (with-open-file (stream cache-file-name
828 :direction :output
829 :if-exists :supersede)
830 (prin1 place stream))))
832 (defmacro restore-place (place filename-stump &optional default)
833 "Restore place from a file whose name is based on symbol filename-stump."
834 `(with-open-file (stream (cache-file-name ,filename-stump)
835 :direction :input
836 :if-does-not-exist nil)
837 (if stream
838 (setf ,place (read stream))
839 (setf ,place ,default))))
841 (defun save-road-section-selection ()
842 "Save the list of road sections selected for processing."
843 (save-place *road-section-selection* 'road-section-selection))
845 (defun restore-road-section-selection ()
846 (restore-place *road-section-selection* 'road-section-selection))
848 (defun update-road-section-selection ()
849 (with-statusbar-message "restoring road section selection"
850 (with-spinner "road_section_spinner"
851 (ignore-errors
852 (with-connection *postgresql-road-network-credentials*
853 (let ((sections (sections (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))))
854 (loop
855 for row-number from 0 below (length sections)
857 (if (find row-number *road-section-selection*)
858 (pipeglade-out "road_sections" "set" row-number 4 1)
859 (pipeglade-out "road_sections" "set" row-number 4 0))))))
860 (pipeglade-out "road_sections" "scroll"
861 (or (ignore-errors (apply #'min *road-section-selection*))
863 0))))
865 (defun restore-road-section-image-counts ()
866 (with-statusbar-message "restoring road section image counts"
867 (ignore-errors
868 (with-connection *postgresql-road-network-credentials*
869 (let* ((table (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))
870 (sections (sections table)))
871 (loop
872 for (vnk nnk) in sections
873 for row-number from 0
874 do (multiple-value-bind (rearview-image-data rearview-cached-p)
875 (road-section-image-data (provenience-string *phoros-url*) table vnk nnk 10 t :from-cache-only t)
876 (multiple-value-bind (frontview-image-data frontview-cached-p)
877 (road-section-image-data (provenience-string *phoros-url*) table vnk nnk 10 nil :from-cache-only t)
878 (when (and rearview-cached-p frontview-cached-p)
879 (pipeglade-out "road_sections" "set" row-number 3 (+ (length rearview-image-data) (length frontview-image-data))))))))))))
881 (defun save-road-network-credentials (modifiedp)
882 (setf (db-credentials-modifiedp *postgresql-road-network-credentials*) modifiedp)
883 (save-place *postgresql-road-network-credentials* 'road-network-credentials))
885 (defun restore-road-network-credentials ()
886 (restore-place *postgresql-road-network-credentials* 'road-network-credentials))
888 (defun save-zeb-credentials (modifiedp)
889 (setf (db-credentials-modifiedp *postgresql-zeb-credentials*) modifiedp)
890 (save-place *postgresql-zeb-credentials* 'zeb-credentials))
892 (defun restore-zeb-credentials ()
893 (restore-place *postgresql-zeb-credentials* 'zeb-credentials))
895 (defun save-accidents-credentials (modifiedp)
896 (setf (db-credentials-modifiedp *postgresql-accidents-credentials*) modifiedp)
897 (save-place *postgresql-accidents-credentials* 'accidents-credentials))
899 (defun restore-accidents-credentials ()
900 (restore-place *postgresql-accidents-credentials* 'accidents-credentials))
902 (defun save-phoros-credentials ()
903 (save-place *phoros-credentials* 'phoros-credentials)
904 (save-place *phoros-url* 'phoros-url))
906 (defun restore-phoros-credentials ()
907 (restore-place *phoros-credentials* 'phoros-credentials)
908 (restore-place *phoros-url* 'phoros-url))
910 (defun save-road-section ()
911 "Save road-section into cache directory."
912 (save-place *road-section* 'road-section))
914 (defun restore-road-section ()
915 (restore-place *road-section* 'road-section))
917 (defun save-accidents-chart-configuration ()
918 (save-place *accidents-chart-configuration* 'accidents-chart-configuration))
920 (defun save-station (station)
921 "Save position of chart cursor into cache directory."
922 (save-place station 'station))
924 (defun saved-station ()
925 (let ((cache-file-name (cache-file-name 'station))
926 station)
927 (ensure-directories-exist cache-file-name)
928 (with-open-file (stream cache-file-name
929 :direction :input
930 :if-does-not-exist nil)
931 (when stream (setf station (read stream)))
932 (or station 0))))
934 (defun restore-road-network-chart-configuration ()
935 (unless (db-credentials-modifiedp *postgresql-road-network-credentials*)
936 (restore-place *road-network-chart-configuration* 'road-network-chart-configuration)))
938 (defun restore-zeb-chart-configuration ()
939 (unless (db-credentials-modifiedp *postgresql-zeb-credentials*)
940 (restore-place *zeb-chart-configuration* 'zeb-chart-configuration)))
942 (defun restore-accidents-chart-configuration ()
943 (unless (db-credentials-modifiedp *postgresql-accidents-credentials*)
944 (restore-place *accidents-chart-configuration* 'accidents-chart-configuration (list "1" "1999" "2030"))))
946 (defun set-road-section (&key direction)
947 (let* ((table (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))
948 (sections (sections table))
949 (sections-current (position (cdr *road-section*) sections :test #'equal))
950 (selection-current (position sections-current *road-section-selection*)))
951 (cond ((and *road-section-selection* (eq direction :predecessor))
952 (let ((selection-predecessor (ignore-errors (nth (1- selection-current) *road-section-selection*))))
953 (when selection-predecessor
954 (setf *road-section*
955 (cons table (nth selection-predecessor sections))))))
956 ((and *road-section-selection* (eq direction :successor))
957 (let* ((selection-successor (nth (1+ selection-current) *road-section-selection*)))
958 (when selection-successor
959 (setf *road-section*
960 (cons table (nth selection-successor sections))))))
961 ((and *road-section-selection* (eq direction :last))
962 (setf *road-section* (cons table
963 (nth (car (last *road-section-selection*)) sections))))
964 (*road-section-selection*
965 (setf *road-section* (cons table
966 (nth (first *road-section-selection*) sections))))
968 (setf *road-section* nil)))))
970 (let (old-road-section)
971 (defun update-station (&optional station)
972 "If either station is supplied or *road-section* has changed, change station widget in UI. Return nil if nothing has been changed"
973 (cond ((numberp station)
974 (setf old-road-section *road-section*)
975 (pipeglade-out "station_scale" "set_value" station)
976 (save-station station))
977 ((not (and old-road-section
978 (equal (cdr *road-section*) (cdr old-road-section))
979 (equal (string (car *road-section*)) (string (car *road-section*))))) ;comparing uninterned symbols
980 (setf old-road-section *road-section*)
981 (pipeglade-out "station_scale" "set_value" 0)
982 (save-station 0))
984 nil))))
986 (defun check-db (db-credentials &aux result)
987 "Check database connection and presence of table or view table-name.
988 Return a string describing the outcome."
989 (let ((table-name (db-credentials-table db-credentials)))
990 (unless
991 (ignore-errors
992 (with-connection db-credentials
993 (if (or (table-exists-p table-name)
994 (view-exists-p table-name))
995 (setf result "ok")
996 (setf result "table or view missing"))))
997 (setf result "connection failure"))
998 result))
1000 (defun check-phoros (url user-name password)
1001 "Check connection to phoros server. Return a string describing the
1002 outcome."
1003 (let ((*phoros-url* url)
1004 (*phoros-cookies* nil))
1005 (unwind-protect
1006 (handler-case (phoros-login url user-name password)
1007 (usocket:ns-host-not-found-error () "host not found")
1008 (usocket:connection-refused-error () "connection refused")
1009 (error (c) (format nil "~A" c))
1010 (:no-error (result) (if result "ok" "wrong user or password")))
1011 (ignore-errors (phoros-logout)))))
1013 (defun populate-chart-dialog ()
1014 (with-statusbar-message "initialising chart configuration"
1015 (update-chart-dialog-treeview "road_network" *postgresql-road-network-credentials* *road-network-chart-configuration*)
1016 (update-chart-dialog-treeview "zeb" *postgresql-zeb-credentials* *zeb-chart-configuration*)
1017 (update-accidents-chart-dialog)))
1020 (defun update-chart-dialog ()
1021 (with-statusbar-message "updating chart configuration"
1022 (when (db-credentials-modifiedp *postgresql-road-network-credentials*)
1023 (update-chart-dialog-treeview "road_network" *postgresql-road-network-credentials* *road-network-chart-configuration*)
1024 (save-road-network-credentials nil))
1025 (when (db-credentials-modifiedp *postgresql-zeb-credentials*)
1026 (update-chart-dialog-treeview "zeb" *postgresql-zeb-credentials* *zeb-chart-configuration*)
1027 (save-zeb-credentials nil))
1028 (when (db-credentials-modifiedp *postgresql-accidents-credentials*)
1029 (update-accidents-chart-dialog)
1030 (save-accidents-credentials nil))))
1032 (defun update-chart-dialog-treeview (treeview db-credentials chart-configuration)
1033 (with-statusbar-message "updating chart configuration"
1034 (ignore-errors
1035 (with-connection db-credentials
1036 (present-db-columns (table-description (db-credentials-table db-credentials)) treeview chart-configuration)))))
1039 (defun update-accidents-chart-dialog ()
1040 (pipeglade-out "render_accidents" "set_active" (first *accidents-chart-configuration*))
1041 (pipeglade-out "accidents_from" "set_text" (second *accidents-chart-configuration*))
1042 (pipeglade-out "accidents_to" "set_text" (third *accidents-chart-configuration*)))
1044 (defun present-db-columns (columns treeview chart-configuration)
1045 (pipeglade-out treeview "clear")
1046 (loop
1047 for (column-name type) in (sort columns #'string-lessp :key #'car)
1048 for row-number from 0
1050 (let ((selected-column (find column-name chart-configuration :key #'data-style-name :test #'string-equal))
1051 (drawablep (numeric-type-p type)))
1052 (pipeglade-out treeview "set" row-number 0 column-name)
1053 (pipeglade-out treeview "set" row-number 1 type)
1054 (pipeglade-out treeview "set" row-number 2 (or (data-style-width selected-column) 2))
1055 (pipeglade-out treeview "set" row-number 3 (or (data-style-color selected-column) "black"))
1056 (pipeglade-out treeview "set" row-number 4 (or (data-style-dash selected-column) ""))
1057 (pipeglade-out treeview "set" row-number 5 (if (and drawablep (data-style-chartp selected-column)) 1 0))
1058 (pipeglade-out treeview "set" row-number 6 (if (data-style-textp selected-column) 1 0))
1059 (pipeglade-out treeview "set" row-number 7 (if drawablep 1 0))
1060 (pipeglade-out treeview "set_cursor" row-number))) ;tickle initial pipeglade output
1061 (pipeglade-out treeview "set_cursor")
1062 (pipeglade-out treeview "scroll" 0 0))
1064 (defun numeric-type-p (type)
1065 (some #'identity (mapcar (lambda (x) (search x type))
1066 '("float" "double" "int" "numeric" "serial"))))
1068 (defun add-vnk-nnk-leaf (vnk nnk length row-number)
1069 "Put a leaf into road-sections tree."
1070 (pipeglade-out "road_sections" "set" row-number 0 vnk)
1071 (pipeglade-out "road_sections" "set" row-number 1 nnk)
1072 (pipeglade-out "road_sections" "set" row-number 2 length))
1074 (defun prepare-chart ()
1075 "Prepare chart for the road section between vnk and nnk in table in
1076 current database."
1077 (when *road-section*
1078 (destructuring-bind (table vnk nnk road-section-length) *road-section*
1079 (pipeglade-out "ovl_chart" "set_size_request" (+ *chart-tail* road-section-length) (+ *chart-height* *chart-fringe*))
1080 (pipeglade-out "vnk" "set_text" vnk)
1081 (pipeglade-out "nnk" "set_text" nnk)
1082 (pipeglade-out "length" "set_text" road-section-length)
1083 (draw-chart-cursor-scale road-section-length)
1084 (pipeglade-out "station_scale" "set_range" 0 road-section-length)
1085 (setf *road-section* (list table vnk nnk road-section-length))
1086 (save-road-section)
1087 (draw-graphs vnk nnk)
1088 (pipeglade-out "station_scale" "set_value" (saved-station)))))
1090 (defun place-chart-cursor (station)
1091 "Move chart cursor to station."
1092 (when station
1093 (pipeglade-out "chart_cursor" "remove" 2)
1094 (pipeglade-out "chart_cursor" "move_to" 2 station 0)
1095 (pipeglade-out "chart_cursor" "line_to" 2 station (+ *chart-height* *chart-fringe*))
1096 (pipeglade-out "chart_cursor" "stroke" 2)
1097 (pipeglade-out "chart_scroll" "hscroll_to_range" (- station 200) (+ station 200))
1098 (pipeglade-out "chart_road_network_scale" "translate" "=3" station 0)
1099 (pipeglade-out "chart_zeb_scale" "translate" "=3" station 0)))
1101 (defun refresh-chart ()
1102 "Redraw chart."
1103 (when (= (length *road-section*) 4)
1104 (prepare-chart)))
1106 (defun draw-graphs (vnk nnk)
1107 "Draw graphs for the columns in *zeb-chart-configuration* and
1108 *road-network-chart-configuration*. Delete existing graphs first."
1109 (with-statusbar-message "drawing chart"
1110 (with-spinner "chart_spinner"
1111 (pipeglade-out "chart_road_network" "remove" 2)
1112 (pipeglade-out "chart_road_network_scale" "remove" 2)
1113 (pipeglade-out "chart_road_network_scale" "translate" "=3" 0 0)
1114 (pipeglade-out "chart_zeb" "remove" 2)
1115 (pipeglade-out "chart_zeb_scale" "remove" 2)
1116 (pipeglade-out "chart_zeb_scale" "translate" "=3" 0 0)
1117 (let ((scale-position *scale-distance*))
1118 (with-statusbar-message "drawing road-network chart"
1119 (when (vectorp *road-network-chart-configuration*)
1120 (loop
1121 for style-definition across *road-network-chart-configuration*
1123 (when (data-style-chartp style-definition)
1124 (ignore-errors
1125 (draw-graph #'road-network-chart-data "chart_road_network" (data-style-name style-definition) vnk nnk (data-style-color style-definition) (data-style-width style-definition) (data-style-dash style-definition))
1126 (draw-scale scale-position #'road-network-chart-data "chart_road_network_scale" (data-style-name style-definition) vnk nnk (data-style-color style-definition) (data-style-width style-definition) (data-style-dash style-definition))
1127 (incf scale-position *scale-distance*))))))
1128 (with-statusbar-message "drawing zeb chart"
1129 (when (vectorp *zeb-chart-configuration*)
1130 (loop
1131 for style-definition across *zeb-chart-configuration*
1133 (when (data-style-chartp style-definition)
1134 (ignore-errors
1135 (draw-graph #'zeb-chart-data "chart_zeb" (data-style-name style-definition) vnk nnk (data-style-color style-definition) (data-style-width style-definition) (data-style-dash style-definition))
1136 (draw-scale scale-position #'zeb-chart-data "chart_zeb_scale" (data-style-name style-definition) vnk nnk (data-style-color style-definition) (data-style-width style-definition) (data-style-dash style-definition))
1137 (incf scale-position *scale-distance*)))))))
1138 (pipeglade-out "chart_accidents" "remove" 2)
1139 (ignore-errors
1140 (draw-accidents vnk nnk)))))
1142 (defun draw-graph (chart-data-function chart column vnk nnk color width dash)
1143 (multiple-value-bind (line minimum maximum)
1144 (funcall chart-data-function column vnk nnk *chart-height*)
1145 (let ((line-fragments
1146 (cl-utilities:split-sequence-if #'(lambda (x)
1147 (eq (second x) :null))
1148 line
1149 :remove-empty-subseqs t)))
1150 (pipeglade-out chart "set_source_rgba" 2 color)
1151 (pipeglade-out chart "set_line_width" 2 width)
1152 (pipeglade-out chart "set_dash" 2 dash)
1153 (dolist (line-fragment line-fragments)
1154 (pipeglade-out chart "move_to" 2 (first (car line-fragment)) (second (car line-fragment)))
1155 (dolist (line-vertex (cdr line-fragment))
1156 (pipeglade-out chart "line_to" 2 (first line-vertex) (second line-vertex)))
1157 (pipeglade-out chart "stroke" 2)))))
1159 (defun draw-scale (position chart-data-function chart column vnk nnk color width dash)
1160 (multiple-value-bind (line minimum maximum)
1161 (funcall chart-data-function column vnk nnk *chart-height*)
1162 (pipeglade-out chart "set_source_rgba" 2 color)
1163 (pipeglade-out chart "set_line_width" 2 width)
1164 (pipeglade-out chart "move_to" 2 position 0)
1165 (pipeglade-out chart "line_to" 2 position *chart-height*)
1166 (dolist (tick (axis-ticks minimum maximum 5 *chart-height* t))
1167 (pipeglade-out chart "move_to" 2 position (format nil "~F" (second tick)))
1168 (pipeglade-out chart "rel_line_to" 2 (* 2 (parse-integer width)) 0)
1169 (pipeglade-out chart "move_to" 2 position (format nil "~F" (second tick)))
1170 (pipeglade-out chart "rel_move_to" 2 (- (parse-integer width)) 0)
1171 (pipeglade-out chart "rel_move_for" 2 "e" (first tick))
1172 (pipeglade-out chart "show_text" 2 (first tick)))
1173 (pipeglade-out chart "move_to" 2 position (format nil "~F" (+ *chart-height* (/ *chart-fringe* 2))))
1174 (pipeglade-out chart "rel_move_for" 2 "c" column)
1175 (pipeglade-out chart "show_text" 2 column)
1176 (pipeglade-out chart "stroke" 2)))
1178 (defun draw-chart-cursor-scale (length)
1179 (let ((y-position (+ *chart-height* *chart-fringe*))
1180 (number-of-ticks (round length 100)))
1181 (pipeglade-out "chart_cursor" "remove" 4)
1182 (dolist (tick (axis-ticks 0 length number-of-ticks length nil))
1183 (pipeglade-out "chart_cursor" "move_to" 4 (second tick) y-position)
1184 (pipeglade-out "chart_cursor" "line_to" 4 (second tick) (- y-position 3))
1185 (pipeglade-out "chart_cursor" "rel_move_for" 4 "s" (first tick))
1186 (pipeglade-out "chart_cursor" "show_text" 4 (first tick)))
1187 (pipeglade-out "chart_cursor" "stroke" 4)))
1189 (defun axis-ticks (minimum maximum n chart-size reversep)
1190 (let ((range (- maximum minimum)))
1191 (if (zerop range)
1192 (list (list (format nil "~F" minimum) (/ chart-size 2)))
1193 (let* ((a (if reversep
1194 (- (/ chart-size range))
1195 (/ chart-size range)))
1196 (b (if reversep
1197 (* a maximum)
1198 (- (* a maximum) chart-size)))
1199 (min-step (/ range (1+ n)))
1200 (max-step (/ range (1- n)))
1201 (max-exp (log max-step 10))
1202 (int-exp (floor max-exp))
1203 (norm-min (floor (/ min-step (expt 10 int-exp))))
1204 (norm-max (floor (/ max-step (expt 10 int-exp))))
1205 (norm (cond
1206 ((or (= norm-min 1) (= norm-max 1))
1208 ((or (<= norm-min 4 norm-max) (<= norm-min 5 norm-max) (<= norm-min 6 norm-max))
1210 ((or (<= norm-min 2) (<= norm-min 3 norm-max))
1211 2.5)
1212 ((<= 7 norm-max)
1215 norm-max))) ;can't happen
1216 (step (* norm (expt 10 int-exp)))
1217 (start (- minimum (nth-value 1 (fceiling minimum step)))))
1218 (loop
1219 for i from start to maximum by step
1220 collect (list (if (minusp int-exp)
1221 (format nil "~,VF" (- int-exp) i)
1222 (format nil "~A" (round i)))
1223 (- (* a i) b)))))))
1225 (defun draw-accidents (vnk nnk)
1226 (when (string-equal (first *accidents-chart-configuration*) "1")
1227 (let* ((year-min (second *accidents-chart-configuration*))
1228 (year-max (third *accidents-chart-configuration*))
1229 (accidents (accidents-data vnk nnk :year-min year-min :year-max year-max))
1230 (current-station -1)
1231 (zeroth-position -1)
1232 y1-position
1233 y2-position)
1234 (dolist (accident accidents)
1235 (unless (= current-station (getf accident :nk-station))
1236 (setf y1-position (- *chart-height* zeroth-position))
1237 (setf y2-position zeroth-position)
1238 (setf y0-position (+ (/ *chart-height* 2) zeroth-position)))
1239 (setf current-station (getf accident :nk-station))
1240 (cond ((= 1 (getf accident :fahrtrichtung))
1241 (draw-accident accident (decf y1-position 10)))
1242 ((= 2 (getf accident :fahrtrichtung))
1243 (draw-accident accident (incf y2-position 10)))
1245 (draw-accident accident (incf y0-position 10))))))))
1247 (defun draw-accident (accident y-position)
1248 "Put graphical representation of accident on chart."
1249 (destructuring-bind (&key nk-station fahrtrichtung unfalltyp unfallkategorie alkohol)
1250 accident
1251 (when (and (numberp alkohol) (plusp alkohol)) (draw-triangle nk-station y-position "lightblue"))
1252 (case unfallkategorie
1253 (1 (draw-rectangle nk-station y-position 10 "black")
1254 (draw-circle nk-station y-position 8 (accident-type-color unfalltyp)))
1255 (2 (draw-circle nk-station y-position 8 (accident-type-color unfalltyp)))
1256 (3 (draw-circle nk-station y-position 6 (accident-type-color unfalltyp)))
1257 (4 (draw-circle nk-station y-position 6 "white")
1258 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1259 (5 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1260 (6 (draw-triangle nk-station y-position "lightblue")
1261 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1262 (t (draw-circle nk-station y-position 4 (accident-type-color unfalltyp))))))
1264 (defun draw-circle (x y diameter color)
1265 (pipeglade-out "chart_accidents" "set_source_rgba" 2 "black")
1266 (pipeglade-out "chart_accidents" "arc" 2 x y (/ diameter 2) 0 360)
1267 (pipeglade-out "chart_accidents" "stroke_preserve" 2)
1268 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1269 (pipeglade-out "chart_accidents" "fill" 2))
1271 (defun draw-rectangle (x y diameter color)
1272 (let ((radius (/ diameter 2)))
1273 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1274 (pipeglade-out "chart_accidents" "rectangle" 2 (- x radius) (- y radius) diameter diameter)
1275 (pipeglade-out "chart_accidents" "fill" 2)))
1277 (defun draw-triangle (x y color)
1278 (pipeglade-out "chart_accidents" "set_source_rgba" 2 "black")
1279 (pipeglade-out "chart_accidents" "move_to" 2 (- x 3) (- y 6))
1280 (pipeglade-out "chart_accidents" "line_to" 2 (+ x 3) (- y 6))
1281 (pipeglade-out "chart_accidents" "line_to" 2 x (+ y 9))
1282 (pipeglade-out "chart_accidents" "close_path" 2)
1283 (pipeglade-out "chart_accidents" "stroke_preserve" 2)
1284 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1285 (pipeglade-out "chart_accidents" "fill" 2))
1287 (defun accident-type-color (accident-type)
1288 (case accident-type
1289 (1 "green")
1290 (2 "yellow")
1291 (3 "red")
1292 (4 "white")
1293 (5 "lightblue")
1294 (6 "orange")
1295 (7 "black")
1296 (t "darkblue")))
1298 (defun jump-to-station (station &key synchronous)
1299 (when *cruise-control-thread*
1300 (unless synchronous
1301 (return-from jump-to-station)) ;ignore effect of updating station_scale while cruise-controlling
1302 (pipeglade-out "station_scale" "set_value" station))
1303 (save-station station)
1304 (and (bt:threadp *jump-to-station-thread*) (bt:thread-alive-p *jump-to-station-thread*) (bt:destroy-thread *jump-to-station-thread*))
1305 (unless
1306 (ignore-errors
1307 (setf *jump-to-station-thread*
1308 (bt:make-thread
1309 (lambda ()
1310 (let ((table (first *road-section*))
1311 (vnk (second *road-section*))
1312 (nnk (third *road-section*)))
1313 (pipeglade-out "station" "set_text" station)
1314 (place-chart-cursor station)
1315 (if *show-rear-view-p*
1316 (ignore-errors (put-image :vnk vnk :nnk nnk :station station :step 10 :rear-view-p t))
1317 (progn
1318 (pipeglade-out "draw_rearview" "remove" 2)
1319 (pipeglade-out "img_rearview" "set_from_file")))
1320 (if *show-front-view-p*
1321 (ignore-errors (put-image :vnk vnk :nnk nnk :station station :step 10 :rear-view-p nil))
1322 (progn
1323 (pipeglade-out "draw_frontview" "remove" 2)
1324 (pipeglade-out "img_frontview" "set_from_file")))
1325 (put-text-values vnk nnk station)))))
1326 (when synchronous
1327 (bt:join-thread *jump-to-station-thread*)
1328 (and (bt:threadp *rear-view-image-thread*) (bt:join-thread *rear-view-image-thread*))
1329 (and (bt:threadp *front-view-image-thread*) (bt:join-thread *front-view-image-thread*)))
1331 (clear-main-window)))
1333 (defun cruise-control (&key backwardp)
1334 (let ((road-section-length (fourth *road-section*)))
1335 (setf *cruise-control-thread*
1336 (bt:make-thread
1337 (lambda ()
1338 (loop
1340 (jump-to-station (+ (if backwardp (- *big-step*) *big-step*)
1341 (saved-station)) :synchronous t)
1342 (jump-to-station (+ (if backwardp (- *big-step*) *big-step*)
1343 (saved-station)) :synchronous t)
1344 while (<= (+ 0 *big-step*) (saved-station) (- road-section-length *big-step*))))))))
1346 (defun stop-cruise-control ()
1347 (and (bt:threadp *cruise-control-thread*) (bt:thread-alive-p *cruise-control-thread*) (bt:destroy-thread *cruise-control-thread*))
1348 (setf *cruise-control-thread* nil))
1350 (defun put-image (&key vnk nnk station step rear-view-p)
1351 "Put an image along with a labelled station marker on screen."
1352 (with-connection *postgresql-road-network-credentials*
1353 (setf station (or station 0))
1354 (let* ((table (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))
1355 (point-radius 5)
1356 (image-widget (if rear-view-p "img_rearview" "img_frontview"))
1357 (drawing-widget (if rear-view-p "draw_rearview" "draw_frontview"))
1358 (spinner-widget (if rear-view-p "spinner_rearview" "spinner_frontview"))
1359 (time-widget (if rear-view-p "rear_view_time" "front_view_time"))
1360 (global-point-coordinates
1361 (subseq (all-stations table vnk nnk)
1362 (min (length (all-stations table vnk nnk)) station)
1363 (min (length (all-stations table vnk nnk)) (+ station 4))))
1364 (image-data-alist
1365 (get-image-data-alist (road-section-image-data (provenience-string *phoros-url*) table vnk nnk step rear-view-p)
1366 station
1367 step))
1368 (image-arrow-coordinates
1369 (loop
1370 for i across global-point-coordinates
1371 append (image-point-coordinates image-data-alist i)))
1372 (image-label-coordinates (ignore-errors
1373 (list (- (first image-arrow-coordinates) point-radius)
1374 (- (second image-arrow-coordinates) point-radius))))
1375 (image-data (get-image-data (road-section-image-data (provenience-string *phoros-url*) table vnk nnk step rear-view-p) station step)))
1376 (if image-data
1377 (progn
1378 (unless (image-launched-p image-data rear-view-p)
1379 (if rear-view-p
1380 (and (bt:threadp *rear-view-image-thread*) (bt:thread-alive-p *rear-view-image-thread*) (bt:destroy-thread *rear-view-image-thread*))
1381 (and (bt:threadp *front-view-image-thread*) (bt:thread-alive-p *front-view-image-thread*) (bt:destroy-thread *front-view-image-thread*)))
1382 (let ((thread
1383 (bt:make-thread (lambda ()
1384 (with-spinner spinner-widget
1385 (remember-image-being-launched image-data rear-view-p)
1386 (let ((image-filename (ignore-errors
1387 (when image-data (namestring (download-image image-data))))))
1388 (if image-filename
1389 (pipeglade-out image-widget "set_from_file" image-filename)
1390 (pipeglade-out image-widget "set_from_file" "public_html/phoros-logo-background.png"))))))))
1391 (if rear-view-p
1392 (setf *rear-view-image-thread* thread)
1393 (setf *front-view-image-thread* thread))))
1394 (pipeglade-out time-widget "set_text" (iso-time (image-data-trigger-time image-data)))
1395 (pipeglade-out drawing-widget "remove" 2)
1396 (when image-arrow-coordinates
1397 (pipeglade-out drawing-widget "move_to" 2 (first image-arrow-coordinates) (second image-arrow-coordinates))
1398 (pipeglade-out drawing-widget "line_to" 2 (first (last image-arrow-coordinates 2)) (second (last image-arrow-coordinates 2)))
1399 (pipeglade-out drawing-widget "stroke" 2)
1400 (pipeglade-out drawing-widget "arc" 2 (first image-arrow-coordinates) (second image-arrow-coordinates) point-radius 0 360)
1401 (pipeglade-out drawing-widget "stroke" 2)
1402 (pipeglade-out drawing-widget "move_to" 2 (first image-label-coordinates) (second image-label-coordinates))
1403 (pipeglade-out drawing-widget "rel_move_for" 2 "se" station)
1404 (pipeglade-out drawing-widget "show_text" 2 station)))
1405 (progn
1406 (pipeglade-out image-widget "set_from_file" "public_html/phoros-logo-background.png")
1407 (pipeglade-out time-widget "set_text")
1408 (pipeglade-out drawing-widget "remove" 2))))))
1410 (defun iso-time (time)
1411 (multiple-value-bind (seconds deciseconds)
1412 (floor time)
1413 (multiple-value-bind (second minute hour date month year day daylight-p zone)
1414 (decode-universal-time seconds)
1415 (format nil "~D-~2,'0D-~2,'0D\\n~2,'0D:~2,'0D:~2,'0D~3,3FZ" year month date hour minute second deciseconds))))
1417 (defun image-point-coordinates (image-data-alist global-point-coordinates)
1418 "Return a list (m n) of image coordinates representing
1419 global-point-coordinates in the image described in image-data-alist
1420 but scaled to fit into *image-size*."
1421 (ignore-errors
1422 (convert-image-coordinates
1423 (photogrammetry :reprojection
1424 image-data-alist
1425 (pairlis '(:x-global :y-global :z-global)
1426 (proj:cs2cs
1427 (list
1428 (proj:degrees-to-radians
1429 (coordinates-longitude global-point-coordinates))
1430 (proj:degrees-to-radians
1431 (coordinates-latitude global-point-coordinates))
1432 (coordinates-ellipsoid-height global-point-coordinates))
1433 :destination-cs (cdr (assoc :cartesian-system image-data-alist)))))
1434 image-data-alist)))
1436 (defun in-image-p (m n)
1437 "Check if m, n lay inside *image-size*."
1438 (and m n (<= 0 m (first *image-size*)) (<= 0 n (second *image-size*))))
1440 (defun-cached sections (table)
1441 "Return list of distinct pairs of vnk, nnk found in table in
1442 current database."
1443 (ignore-errors
1444 (query (:order-by (:select 'vnk 'nnk (:max 'nk-station)
1445 :from (db-credentials-table *postgresql-road-section-credentials*)
1446 :where (:and (:not-null 'vnk) (:not-null 'nnk))
1447 :group-by 'vnk 'nnk)
1448 'vnk 'nnk))))
1450 (defun stations (table vnk nnk &optional (step 1))
1451 "Return a list of plists of :longitude, :latitude,
1452 :ellipsoid-height, :station, :azimuth of stations step metres apart
1453 between vnk and nnk."
1454 (let ((stations
1455 (query
1456 (:order-by
1457 (:select (:as (:st_x 't1.the-geom) 'longitude)
1458 (:as (:st_y 't1.the-geom) 'latitude)
1459 (:as (:st_z 't1.the-geom) 'ellipsoid-height)
1460 (:as 't1.nk-station 'station)
1461 (:as (:st_azimuth 't1.the-geom 't2.the-geom) 'azimuth)
1462 :from (:as table 't1)
1463 :left-join (:as table 't2)
1464 :on (:and (:= 't1.nk-station (:- 't2.nk-station 1))
1465 (:= 't2.vnk vnk)
1466 (:= 't2.nnk nnk))
1467 :where (:and (:= 't1.vnk vnk)
1468 (:= 't1.nnk nnk)
1469 (:= 0 (:% 't1.nk-station step))))
1470 't1.nk-station)
1471 :plists)))
1472 (setf
1473 (getf (nth (- (length stations) 1) stations) :azimuth)
1474 (getf (nth (- (length stations) 2) stations) :azimuth))
1475 stations))
1477 (defun-cached all-stations (table vnk nnk)
1478 "Return a vector of coordinates of all points between vnk and nnk,
1479 station (in metres) being the vector index."
1480 (let* ((stations (stations table vnk nnk))
1481 (result (make-array (list (1+ (getf (first (last stations)) :station)))
1482 :initial-element nil)))
1483 (loop
1484 for i in stations
1485 do (destructuring-bind (&key longitude latitude ellipsoid-height station azimuth)
1487 (setf (svref result station)
1488 (make-coordinates :longitude longitude
1489 :latitude latitude
1490 :ellipsoid-height ellipsoid-height
1491 :azimuth azimuth))))
1492 result))
1494 (defun-cached road-section-image-data (provenience-string table vnk nnk step rear-view-p)
1495 "Return a list of instances of image data corresponding to stations,
1496 which are step metres apart, found in table in current database.
1497 provenience-string only serves as a marker of the provenience of image
1498 data once cached."
1499 (remove nil ;; (mapcar #'(lambda (x)
1500 ;; (apply #'image-data :rear-view-p rear-view-p x))
1501 ;; (stations table vnk nnk step))
1502 (loop
1503 with azimuth-fallback = nil
1504 for station in (stations table vnk nnk step)
1505 when (not (eq (getf station :azimuth) :null))
1506 do (setf azimuth-fallback (getf station :azimuth))
1507 and collect (apply #'image-data :rear-view-p rear-view-p station)
1509 when (and azimuth-fallback
1510 (eq (getf station :azimuth) :null))
1511 do (setf (getf station :azimuth) azimuth-fallback)
1512 and collect (apply #'image-data :rear-view-p rear-view-p station))))
1514 (defun provenience-string (url)
1515 "Turn url recognisably into something suitable as part of a file
1516 name."
1517 (let ((parsed-url (puri:parse-uri url)))
1518 (format nil "~A_~A~{_~A~}"
1519 (puri:uri-host parsed-url)
1520 (puri:uri-port parsed-url)
1521 (cl-utilities:split-sequence
1522 #\/ (puri:uri-path parsed-url) :remove-empty-subseqs t))))
1524 (defun cache-file-name (kind &rest args)
1525 "Return pathname for a cache file distinguishable by kind and args."
1526 (make-pathname :directory *cache-dir*
1527 :name (format nil "~{~:[f~;~:*~(~A~)~]_~}~A"
1528 args
1529 *fasttrack-version*)
1530 :type (string-downcase kind)))
1532 (defun cache-images (road-section-image-data)
1533 "Download images described in road-section-image-data into their
1534 canonical places."
1535 (loop
1536 for i in road-section-image-data
1537 do (download-image i)))
1539 (defun get-image-data (road-section-image-data station step)
1540 "Return image data for the image near station."
1541 (find (* step (round station step)) road-section-image-data
1542 :key #'image-data-station
1543 :test #'=))
1545 (defun get-image-data-alist (road-section-image-data station step)
1546 "Return as an alist data for the image near station."
1547 (image-data-alist (get-image-data road-section-image-data station step)))
1549 (defun image-data (&key longitude latitude ellipsoid-height station azimuth rear-view-p)
1550 "Get from Phoros server image data for location near longitude,
1551 latitude."
1552 (ignore-errors
1553 (let* ((coordinates (make-coordinates :longitude longitude
1554 :latitude latitude
1555 :ellipsoid-height ellipsoid-height
1556 :azimuth azimuth))
1557 (image-data (phoros-nearest-image-data coordinates rear-view-p)))
1558 (when (image-data-p image-data)
1559 (setf (image-data-station image-data) station)
1560 (setf (image-data-station-coordinates image-data) coordinates)
1561 image-data))))
1563 (define-condition phoros-server-error (error)
1564 ((body :reader body :initarg :body)
1565 (status-code :reader status-code :initarg :status-code)
1566 (headers :reader headers :initarg :headers)
1567 (url :reader url :initarg :url)
1568 (reason-phrase :reader reason-phrase :initarg :reason-phrase))
1569 (:report (lambda (condition stream)
1570 (format stream "Can't connect to Phoros server: ~A (~D)"
1571 (reason-phrase condition) (status-code condition)))))
1573 (defun phoros-lib-url (canonical-url suffix)
1574 "Replace last path element of canonical-url by lib/<suffix>."
1575 (let* ((parsed-canonical-url (puri:parse-uri canonical-url))
1576 (old-path (puri:uri-parsed-path parsed-canonical-url))
1577 (new-path (append (butlast old-path) (list "lib" suffix)))
1578 (new-url (puri:copy-uri parsed-canonical-url)))
1579 (setf (puri:uri-parsed-path new-url) new-path)
1580 new-url))
1582 (defun phoros-login (url user-name user-password)
1583 "Log into Phoros server; return T if successful. Try logging out
1584 first."
1585 ;; (setf *phoros-url* url)
1586 (setf drakma:*allow-dotless-cookie-domains-p* t)
1587 (pushnew (cons "application" "json") drakma:*text-content-types* :test #'equal)
1588 (ignore-errors (phoros-logout))
1589 (setf *phoros-cookies* (make-instance 'drakma:cookie-jar))
1590 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1591 (drakma:http-request (puri:parse-uri url) :cookie-jar *phoros-cookies*)
1592 (declare (ignore stream must-close))
1593 (assert (= status-code 200) ()
1594 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1595 (multiple-value-bind (body status-code headers authenticate-url stream must-close reason-phrase)
1596 (drakma:http-request (phoros-lib-url url "authenticate")
1597 :cookie-jar *phoros-cookies*
1598 :form-data t
1599 :method :post
1600 :parameters (pairlis '("user-name" "user-password")
1601 (list user-name user-password)))
1602 (declare (ignore stream must-close))
1603 (assert (< status-code 400) ()
1604 'phoros-server-error :body body :status-code status-code :headers headers :url authenticate-url :reason-phrase reason-phrase)
1605 (let ((body-strings (cl-utilities:split-sequence #\Space (substitute-if-not #\Space #'alphanumericp body))))
1606 (and (not (find "Rejected" body-strings :test #'string=))
1607 (not (find "Retry" body-strings :test #'string=))
1608 (= status-code 200)))))) ;should be 302 (?)
1610 (defun phoros-logout ()
1611 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1612 (drakma:http-request (phoros-lib-url *phoros-url* "logout"))
1613 (declare (ignore stream must-close))
1614 (assert (= status-code 200) ()
1615 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)))
1617 (defun heading (azimuth rear-view-p)
1618 "Return as a string the one of east, west, north, south which best
1619 describes azimuth."
1620 (cond ((<= (* 1/4 pi) azimuth (* 3/4 pi)) (if rear-view-p "west" "east"))
1621 ((<= (* 3/4 pi) azimuth (* 5/4 pi)) (if rear-view-p "north" "south"))
1622 ((<= (* 5/4 pi) azimuth (* 7/4 pi)) (if rear-view-p "east" "west"))
1623 ((or (<= (* 5/4 pi) azimuth pi) (<= 0 (* 1/4 pi))) (if rear-view-p "south" "north"))))
1625 (defun phoros-nearest-image-data (coordinates rear-view-p)
1626 "Return a set of image-data."
1627 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1628 (drakma:http-request (phoros-lib-url *phoros-url* "nearest-image-data")
1629 :cookie-jar *phoros-cookies*
1630 :method :post
1631 :content-type "text/plain; charset=UTF-8"
1632 :content (json:encode-json-plist-to-string (list :longitude (coordinates-longitude coordinates)
1633 :latitude (coordinates-latitude coordinates)
1634 :zoom 20
1635 :count 1
1636 :selected-restriction-ids (vector "Device_21" (heading (coordinates-azimuth coordinates) rear-view-p))))) ;TODO: document requirement for restrictions tagged north, east, south, west, and front_cam; actually use the latter
1637 (declare (ignore stream must-close))
1638 (assert (= status-code 200) ()
1639 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1640 (unless (string-equal body "null")
1641 (apply #'make-image-data :allow-other-keys t
1642 (plist-from-alist
1643 (car (json:decode-json-from-string body)))))))
1645 (defun download-file (url path)
1646 "Unless already there, store content from url under path. Return
1647 nil if nothing needed storing."
1648 (ensure-directories-exist path)
1649 (with-open-file (file-stream path :direction :output
1650 :element-type 'unsigned-byte
1651 :if-exists nil)
1652 (when file-stream
1653 (multiple-value-bind
1654 (body status-code headers url stream must-close reason-phrase)
1655 (drakma:http-request url
1656 :cookie-jar *phoros-cookies*
1657 :method :get)
1658 (declare (ignore stream must-close))
1659 (setf *t* url)
1660 (assert (= status-code 200) ()
1661 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1662 (write-sequence body file-stream)
1663 reason-phrase))))
1665 (defun download-image (image-data)
1666 "If not already there, download a png image, shrink it, convert it
1667 into jpg, and store it under the cache path. Return that path."
1668 (multiple-value-bind (url origin-path destination-path)
1669 (image-url image-data)
1670 (unless (probe-file destination-path)
1671 (download-file url origin-path)
1672 (apply #'convert-image-file origin-path destination-path *image-size*)
1673 (delete-file origin-path))
1674 destination-path))
1676 (defun image-launched-p (image-data rear-view-p)
1677 "Check if the image belonging to image-data is the current image."
1678 (multiple-value-bind (url origin-path destination-path)
1679 (image-url image-data)
1680 (let ((remembered-image (if rear-view-p
1681 *rear-view-image-path*
1682 *front-view-image-path*)))
1683 (when (and destination-path remembered-image)
1684 (string= (namestring destination-path) (namestring remembered-image))))))
1686 (defun remember-image-being-launched (image-data rear-view-p)
1687 (multiple-value-bind (url origin-path destination-path)
1688 (image-url image-data)
1689 (if rear-view-p
1690 (setf *rear-view-image-path* destination-path)
1691 (setf *front-view-image-path* destination-path))))
1693 (defun forget-images-being-launched ()
1694 (setf *rear-view-image-path* "")
1695 (setf *front-view-image-path* ""))
1697 (defun image-data-alist (image-data)
1698 "Return an alist representation of image-data."
1699 (when image-data
1700 (loop
1701 for i in (append (mapcar #'ensure-hyphen-before-digit *aggregate-view-columns*) '(station station-coordinates))
1702 collect (intern (string i) 'keyword) into keys
1703 collect (funcall (intern (concatenate 'string (string 'image-data-)
1704 (string i)))
1705 image-data)
1706 into values
1707 finally (return (pairlis keys values)))))
1709 (defun plist-from-alist (alist)
1710 (loop
1711 for (key . value) in alist
1712 collect key
1713 collect value))
1715 (defun image-url (image-data)
1716 "Return an image URL made from ingredients found in image-data, the
1717 corresponding cache path, and the corresponding cache path for the
1718 shrunk image."
1719 (let* ((path
1720 (format nil "~A/~A/~A/~D.png"
1721 (puri:uri-path (phoros-lib-url *phoros-url* "photo"))
1722 (image-data-directory image-data)
1723 (image-data-filename image-data)
1724 (image-data-byte-position image-data)))
1725 (query
1726 (format nil "mounting-angle=~D~
1727 &bayer-pattern=~{~D~#^,~}~
1728 &color-raiser=~{~D~#^,~}"
1729 (image-data-mounting-angle image-data)
1730 (map 'list #'identity (image-data-bayer-pattern image-data))
1731 (map 'list #'identity (image-data-color-raiser image-data))))
1732 (url (puri:copy-uri (puri:parse-uri *phoros-url*) :path path :query query))
1733 (host (puri:uri-host url))
1734 (port (puri:uri-port url))
1735 (cache-directory (append *cache-dir*
1736 (list (format nil "~A_~D" host port))
1737 (cdr (pathname-directory (puri:uri-path url)))))
1738 (cache-name (pathname-name (puri:uri-path url)))
1739 (cache-type (pathname-type (puri:uri-path url))))
1740 (values url
1741 (make-pathname :directory cache-directory
1742 :name cache-name
1743 :type cache-type)
1744 (make-pathname :directory cache-directory
1745 :name cache-name
1746 :type "jpg"))))
1748 (defun convert-image-file (origin-file destination-file width height)
1749 "Convert origin-file into destination-file of a maximum size of
1750 width x height."
1751 (lisp-magick-wand:with-magick-wand (wand :load (namestring origin-file))
1752 (let ((a (/ (lisp-magick-wand:get-image-width wand)
1753 (lisp-magick-wand:get-image-height wand))))
1754 (if (> a (/ width height))
1755 (lisp-magick-wand:scale-image wand width (truncate (/ width a)))
1756 (lisp-magick-wand:scale-image wand (truncate (* a height)) height)))
1757 (lisp-magick-wand:write-image wand (namestring destination-file))))
1759 (defun convert-image-coordinates (original-coordinates-alist image-data-alist)
1760 "Convert image coordinates from original-coordinates-alist for the
1761 image in image-data-alist into a list of coordinates for that image
1762 scaled and centered to *image-size*."
1763 (let* ((original-m (cdr (assoc :m original-coordinates-alist)))
1764 (original-n (cdr (assoc :n original-coordinates-alist)))
1765 (original-width (cdr (assoc :sensor-width-pix image-data-alist)))
1766 (original-height (cdr (assoc :sensor-height-pix image-data-alist)))
1767 (new-width (first *image-size*))
1768 (new-height (second *image-size*))
1769 (scaling-factor (min (/ new-width original-width) (/ new-height original-height)))
1770 (new-m-offset (/ (- new-width (* original-width scaling-factor)) 2))
1771 (new-n-offset (/ (- new-height (* original-height scaling-factor)) 2))
1772 (new-m (+ (* original-m scaling-factor) new-m-offset))
1773 (new-n (- new-height ;flip n
1774 (+ (* original-n scaling-factor) new-n-offset))))
1775 (mapcar #'round (list new-m new-n))))