Add missing files to binary tarball
[phoros.git] / fasttrack.lisp
blob06eaa8ce0867cbd1dd03b79b44fd715d14e26241
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 (uiop:run-program "../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 (with-statusbar-message "starting browser"
302 (uiop:run-program (format nil "firefox '~A' &" *phoros-url*)))
303 (loop
304 for message = (read-line in nil)
306 (cond
307 ((message-name= "quit" message)
308 (pipeglade-out "_" "main_quit")
309 (loop-finish))
310 ((message-name= "station_scale" message)
311 (jump-to-station (parse-integer (message-data message) :junk-allowed t)))
312 ((message-name= "show_road_network_chart" message)
313 (pipeglade-out "chart_road_network" "set_visible" (message-info message))
314 (pipeglade-out "chart_road_network_scale" "set_visible" (message-info message)))
315 ((message-name= "show_zeb_chart" message)
316 (pipeglade-out "chart_zeb" "set_visible" (message-info message))
317 (pipeglade-out "chart_zeb_scale" "set_visible" (message-info message)))
318 ((message-name= "show_accidents_chart" message)
319 (pipeglade-out "chart_accidents" "set_visible" (message-info message)))
320 ((message-name= "show_rear_view" message)
321 (setf *show-rear-view-p* (string= (message-info message) "1")))
322 ((message-name= "show_front_view" message)
323 (setf *show-front-view-p* (string= (message-info message) "1")))
324 ((message-name= "big_step" message)
325 (let* ((step (parse-integer (message-data message) :junk-allowed t))
326 (label-text (format nil "~D m" step)))
327 (pipeglade-out "back" "set_label" label-text)
328 (pipeglade-out "forward" "set_label" label-text)
329 (pipeglade-out "big_step_back" "set_label" label-text)
330 (pipeglade-out "big_step_forward" "set_label" label-text)
331 (pipeglade-out "station_scale" "set_increments" 1 step)
332 (setf *big-step* step)))
333 ((message-name= "step_back" message)
334 (stop-cruise-control)
335 (pipeglade-out "station_scale" "set_value" (1- (saved-station))))
336 ((message-name= "step_forward" message)
337 (stop-cruise-control)
338 (pipeglade-out "station_scale" "set_value" (1+ (saved-station))))
339 ((message-name= "big_step_back" message)
340 (stop-cruise-control)
341 (pipeglade-out "station_scale" "set_value" (- (saved-station) *big-step*)))
342 ((message-name= "big_step_forward" message)
343 (stop-cruise-control)
344 (pipeglade-out "station_scale" "set_value" (+ (saved-station) *big-step*)))
345 ((message-name= "back" message)
346 (stop-cruise-control)
347 (cruise-control :backwardp t))
348 ((message-name= "forward" message)
349 (stop-cruise-control)
350 (cruise-control :backwardp nil))
351 ((message-name= "stop" message)
352 (stop-cruise-control))
353 ((message-name= "first_section" message)
354 (set-road-section)
355 (refresh-chart)
356 (pipeglade-out "station_scale" "set_value" 1)
357 (pipeglade-out "station_scale" "set_value" 0))
358 ((message-name= "previous_section" message)
359 (set-road-section :direction :predecessor)
360 (refresh-chart)
361 (pipeglade-out "station_scale" "set_value" 1)
362 (pipeglade-out "station_scale" "set_value" 0))
363 ((message-name= "next_section" message)
364 (set-road-section :direction :successor)
365 (refresh-chart)
366 (pipeglade-out "station_scale" "set_value" 1)
367 (pipeglade-out "station_scale" "set_value" 0))
368 ((message-name= "last_section" message)
369 (set-road-section :direction :last)
370 (refresh-chart)
371 (pipeglade-out "station_scale" "set_value" 1)
372 (pipeglade-out "station_scale" "set_value" 0))
373 ((message-name= "road_sections" message)
374 (collect-road-section-select message))
375 ((message-name= "road_section_ok" message)
376 (digest-road-section-raw-data))
377 ((message-name= "road_section_cncl" message)
378 (restore-road-section-selection)
379 (pipeglade-out "road_section" "set_visible" 0))
380 ((message-name= "road_network" message)
381 (collect-raw-message message *road-network-chart-raw-data*))
382 ((message-name= "zeb" message)
383 (collect-raw-message message *zeb-chart-raw-data*))
384 ((message-name= "render_accidents" message)
385 (setf (first *accidents-chart-raw-data*) (message-info message)))
386 ((message-name= "accidents_from" message)
387 (setf (second *accidents-chart-raw-data*) (message-data message)))
388 ((message-name= "accidents_to" message)
389 (setf (third *accidents-chart-raw-data*) (message-data message)))
390 ((message-name= "chart_configuration_ok" message)
391 (setf *road-network-chart-configuration* (digest-chart-raw-data *road-network-chart-raw-data*))
392 (save-place *road-network-chart-configuration* 'road-network-chart-configuration)
393 (setf *zeb-chart-configuration* (digest-chart-raw-data *zeb-chart-raw-data*))
394 (save-place *zeb-chart-configuration* 'zeb-chart-configuration)
395 (digest-accidents-chart-raw-data)
396 (update-accidents-chart-dialog)
397 (pipeglade-out "text_values" "clear")
398 (refresh-chart))
399 ((message-name= "chart_configuration_cncl" message)
400 (update-accidents-chart-dialog)
401 (setf *accidents-chart-raw-data* (list nil nil nil))
402 (pipeglade-out "chart_configuration" "set_visible" 0))
403 ((message-name= "credentials_check" message)
404 (check-credentials-dialog-statuses))
405 ((message-name= "credentials_ok" message)
406 (check-credentials-dialog-statuses)
407 (when (db-credentials-modifiedp *postgresql-road-network-credentials*)
408 (invalidate-road-section-selection)
409 (invalidate-road-section)
410 (invalidate-road-network-chart-configuration)
411 (populate-road-section-dialog)
412 (update-chart-dialog)
413 (save-road-network-credentials nil))
414 (when (db-credentials-modifiedp *postgresql-zeb-credentials*)
415 (update-chart-dialog)
416 (invalidate-zeb-chart-configuration)
417 (pipeglade-out "text_values" "clear")
418 (refresh-chart)
419 (save-zeb-credentials nil))
420 (when (db-credentials-modifiedp *postgresql-accidents-credentials*)
421 (refresh-chart)
422 (save-accidents-credentials nil))
423 (ignore-errors (apply #'phoros-login *phoros-url* *phoros-credentials*))
424 (forget-images-being-launched)
425 (jump-to-station (saved-station))
426 (update-chart-dialog))
427 ((message-name= "road_network_host" message)
428 (setf (db-credentials-host *postgresql-road-network-credentials*) (message-data message))
429 (save-road-network-credentials t))
430 ((message-name= "road_network_port" message)
431 (setf (db-credentials-port *postgresql-road-network-credentials*) (parse-integer (message-data message)))
432 (save-road-network-credentials t))
433 ((message-name= "road_network_ssl" message)
434 (setf (db-credentials-ssl *postgresql-road-network-credentials*) (message-data message))
435 (save-road-network-credentials t))
436 ((message-name= "road_network_database" message)
437 (setf (db-credentials-database *postgresql-road-network-credentials*) (message-data message))
438 (save-road-network-credentials t))
439 ((message-name= "road_network_user" message)
440 (setf (db-credentials-user *postgresql-road-network-credentials*) (message-data message))
441 (save-road-network-credentials t))
442 ((message-name= "road_network_password" message)
443 (setf (db-credentials-password *postgresql-road-network-credentials*) (message-data message))
444 (save-road-network-credentials t))
445 ((message-name= "road_network_table" message)
446 (setf (db-credentials-table *postgresql-road-network-credentials*) (message-data message))
447 (save-road-network-credentials t))
448 ((message-name= "zeb_host" message)
449 (setf (db-credentials-host *postgresql-zeb-credentials*) (message-data message))
450 (save-zeb-credentials t))
451 ((message-name= "zeb_port" message)
452 (setf (db-credentials-port *postgresql-zeb-credentials*) (parse-integer (message-data message)))
453 (save-zeb-credentials t))
454 ((message-name= "zeb_ssl" message)
455 (setf (db-credentials-ssl *postgresql-zeb-credentials*) (message-data message))
456 (save-zeb-credentials t))
457 ((message-name= "zeb_database" message)
458 (setf (db-credentials-database *postgresql-zeb-credentials*) (message-data message))
459 (save-zeb-credentials t))
460 ((message-name= "zeb_user" message)
461 (setf (db-credentials-user *postgresql-zeb-credentials*) (message-data message))
462 (save-zeb-credentials t))
463 ((message-name= "zeb_password" message)
464 (setf (db-credentials-password *postgresql-zeb-credentials*) (message-data message))
465 (save-zeb-credentials t))
466 ((message-name= "zeb_table" message)
467 (setf (db-credentials-table *postgresql-zeb-credentials*) (message-data message))
468 (save-zeb-credentials t))
469 ((message-name= "accidents_host" message)
470 (setf (db-credentials-host *postgresql-accidents-credentials*) (message-data message))
471 (save-accidents-credentials t))
472 ((message-name= "accidents_port" message)
473 (setf (db-credentials-port *postgresql-accidents-credentials*) (parse-integer (message-data message)))
474 (save-accidents-credentials t))
475 ((message-name= "accidents_ssl" message)
476 (setf (db-credentials-ssl *postgresql-accidents-credentials*) (message-data message))
477 (save-accidents-credentials t))
478 ((message-name= "accidents_database" message)
479 (setf (db-credentials-database *postgresql-accidents-credentials*) (message-data message))
480 (save-accidents-credentials t))
481 ((message-name= "accidents_user" message)
482 (setf (db-credentials-user *postgresql-accidents-credentials*) (message-data message))
483 (save-accidents-credentials t))
484 ((message-name= "accidents_password" message)
485 (setf (db-credentials-password *postgresql-accidents-credentials*) (message-data message))
486 (save-accidents-credentials t))
487 ((message-name= "accidents_table" message)
488 (setf (db-credentials-table *postgresql-accidents-credentials*) (message-data message))
489 (save-accidents-credentials t))
490 ((message-name= "phoros_url" message)
491 (setf *phoros-url* (message-data message))
492 (save-phoros-credentials))
493 ((message-name= "phoros_user" message)
494 (setf (first *phoros-credentials*) (message-data message))
495 (save-phoros-credentials))
496 ((message-name= "phoros_password" message)
497 (setf (second *phoros-credentials*) (message-data message))
498 (save-phoros-credentials))
499 ((message-name= "phoros" message)
500 (run-phoros-browser))
502 (print (list "fallen through:" message)))))))
504 (defun invalidate-road-section ()
505 (setf *road-section* nil)
506 (save-road-section))
508 (defun invalidate-road-section-selection ()
509 (setf *road-section-selection* '())
510 (save-road-section-selection))
512 (defun invalidate-road-network-chart-configuration ()
513 (setf *road-network-chart-configuration* nil)
514 (save-place *road-network-chart-configuration* 'road-network-chart-configuration))
516 (defun invalidate-zeb-chart-configuration ()
517 (setf *zeb-chart-configuration* nil)
518 (save-place *zeb-chart-configuration* 'zeb-chart-configuration))
520 (defun message-name= (string message)
521 (let ((colon-position (position #\: message)))
522 (string= string (subseq message 0 colon-position))))
524 (defun message-info (message)
525 (let ((colon-position (position #\: message))
526 (space-position (position #\Space message)))
527 (subseq message (1+ colon-position) space-position)))
529 (defun message-data (message)
530 (let ((space-position (position #\Space message)))
531 (when space-position
532 (subseq message (1+ space-position)))))
534 (defun message-data-list (message)
535 (cl-utilities:split-sequence #\Space (message-data message)))
537 (defun collect-road-section-select (message)
538 (let ((data (message-data-list message)))
539 (if (string= (second data) "4") ;"select" column
540 (setf (gethash (parse-integer (first data)) ;row number
541 *road-section-raw-data*)
542 (string= (third data) "1")))))
544 (defun collect-accidents-message-data (&key (renderp 0 renderp-p) (from nil from-p) (to nil to-p) (ok-pressed nil ok-pressed-p))
545 (when renderp-p (setf (first *accidents-chart-raw-data*) renderp))
546 (when from-p (setf (second *accidents-chart-raw-data*) (parse-integer from :junk-allowed t)))
547 (when to-p (setf (third *accidents-chart-raw-data*) (parse-integer to :junk-allowed t))))
549 (defun collect-raw-message (message place)
550 (unless (string= (message-info message) "clicked")
551 (let ((data (message-data-list message)))
552 (setf (gethash (list (parse-integer (first data)) ;row number
553 (parse-integer (second data))) ;column number
554 place)
555 (third data)))))
557 (defun digest-road-section-raw-data ()
558 (let ((sections (sections (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))))
559 (maphash (lambda (key value)
560 (if value
561 (pushnew key *road-section-selection*)
562 (setf *road-section-selection* (remove key *road-section-selection*))))
563 *road-section-raw-data*)
564 (setf *road-section-selection* (sort *road-section-selection* #'<))
565 (save-road-section-selection)
566 (set-road-section)
567 (save-road-section)
569 (when (update-station) ;new section
570 (restore-road-section-image-counts)
571 (prepare-chart))
572 (clrhash *road-section-raw-data*)))
574 (defstruct (data-style (:type list)) chartp drawablep textp name color width dash)
576 (defun clear-main-window ()
577 (dolist (drawingarea '("chart_accidents" "chart_road_network" "chart_zeb" "chart_cursor" "chart_road_network_scale" "chart_zeb_scale" "draw_rearview" "draw_frontview"))
578 (pipeglade-out drawingarea "remove" 2))
579 (dolist (image '("img_rearview" "img_frontview"))
580 (pipeglade-out image "set_from_file"))
581 (pipeglade-out "text_values" "clear"))
583 (defun digest-chart-raw-data (raw-data)
584 "Return the information read from raw-data in chart configuration format."
585 (let* ((row-count
586 (loop
587 for (row column) being each hash-key of raw-data
588 when (zerop column) ;arbitrary column representing its row
589 count it))
590 (chart-configuration
591 (make-array (list row-count))))
592 (loop
593 for i from 0 below row-count
595 (setf (svref chart-configuration i)
596 (make-data-style)))
597 (loop
598 for (row column) being each hash-key of raw-data using (hash-value value)
600 (case column
601 (0 ;column name
602 (setf (data-style-name (svref chart-configuration row)) value))
603 ;; 1 would be type
604 (2 ;width
605 (setf (data-style-width (svref chart-configuration row)) value))
606 (3 ;color
607 (setf (data-style-color (svref chart-configuration row)) value))
608 (4 ;dash
609 (setf (data-style-dash (svref chart-configuration row)) value))
610 (5 ;selected
611 (setf (data-style-chartp (svref chart-configuration row)) (string= value "1")))
613 (setf (data-style-textp (svref chart-configuration row)) (string= value "1")))
615 (setf (data-style-drawablep (svref chart-configuration row)) (string= value "1")))))
616 chart-configuration))
618 (defun digest-accidents-chart-raw-data ()
619 (setf *accidents-chart-configuration*
620 (mapcar (lambda (configuration-value raw-value)
621 (or (format nil "~D" (parse-integer raw-value :junk-allowed t)) configuration-value))
622 *accidents-chart-configuration*
623 *accidents-chart-raw-data*))
624 (save-accidents-chart-configuration))
626 (defun road-network-chart-data (column vnk nnk chart-height)
627 "Return a list of lists of station and column values between vnk
628 and nnk scaled into chart-height; the minimum column value; and the
629 maximum column value. Both minimum and maximum are nil if data is
630 constant."
631 (let ((table (intern (db-credentials-table *postgresql-road-network-credentials*))))
632 (with-connection *postgresql-road-network-credentials*
633 (setf column (intern (string-upcase column)))
634 (destructuring-bind (minimum maximum)
635 (query (:select (:type (:min column) real)
636 (:type (:max column) real)
637 :from table
638 :where (:and (:= 'vnk vnk)
639 (:= 'nnk nnk)))
640 :list)
641 (if (and (numberp minimum) (numberp maximum))
642 (let* ((span (- maximum minimum))
643 (m (if (zerop span)
645 (/ chart-height span)))
646 (b (if (zerop span)
647 (* chart-height 1/2)
648 (+ chart-height (* m minimum)))))
649 (values
650 (query (:order-by
651 (:select 'nk-station
652 (:- b (:* m (:type column real)))
653 :from table
654 :where (:and (:= 'vnk vnk)
655 (:= 'nnk nnk)))
656 'nk-station))
657 ;; (unless (zerop span) minimum)
658 ;; (unless (zerop span) maximum)
659 minimum
660 maximum
662 (values nil nil nil))))))
664 (defun zeb-chart-data (column vnk nnk chart-height)
665 "Return a list of lists of station and column values between vnk
666 and nnk scaled into chart-height; the minimum column value; and the
667 maximum column value. Both minimum and maximum are nil if data is
668 constant."
669 (let ((table (intern (db-credentials-table *postgresql-zeb-credentials*))))
670 (with-connection *postgresql-zeb-credentials*
671 (setf column (intern (string-upcase column)))
672 (destructuring-bind (minimum maximum)
673 (query (:select (:type (:min column) real)
674 (:type (:max column) real)
675 :from table
676 :where (:and (:= 'vnk vnk)
677 (:= 'nnk nnk)))
678 :list)
679 (if (and (numberp minimum) (numberp maximum))
680 (let* ((span (- maximum minimum))
681 (m (if (zerop span)
683 (/ chart-height span)))
684 (b (if (zerop span)
685 (* chart-height 1/2)
686 (+ chart-height (* m minimum)))))
687 (values
688 (query (:order-by
689 (:select 'vst
690 (:- b (:* m (:type column real)))
691 'bst
692 (:- b (:* m (:type column real)))
693 :from table
694 :where (:and (:= 'vnk vnk)
695 (:= 'nnk nnk)))
696 'vst))
697 ;; (unless (zerop span) minimum)
698 ;; (unless (zerop span) maximum)
699 minimum
700 maximum
702 (values nil nil nil))))))
706 (defun road-network-text-value (column vnk nnk station)
707 "Return column value at station between vnk and nnk."
708 (let ((table (intern (db-credentials-table *postgresql-road-network-credentials*))))
709 (with-connection *postgresql-road-network-credentials*
710 (setf column (intern (string-upcase column)))
711 (ignore-errors
712 (query (:select column
713 :from table
714 :where (:and (:= 'vnk vnk)
715 (:= 'nnk nnk)
716 (:= 'nk_station station)))
717 :single)))))
719 (defun zeb-text-value (column vnk nnk station)
720 "Return column value at station between vnk and nnk."
721 (let ((table (intern (db-credentials-table *postgresql-zeb-credentials*))))
722 (with-connection *postgresql-zeb-credentials*
723 (setf column (intern (string-upcase column)))
724 (ignore-errors
725 (query (:select column
726 :from table
727 :where (:and (:= 'vnk vnk)
728 (:= 'nnk nnk)
729 (:between station 'vst 'bst)))
730 :single)))))
732 (defun show-text (row-number station text-data-function column vnk nnk color width dash)
733 (let ((value (funcall text-data-function column vnk nnk station)))
734 (pipeglade-out "text_values" "set" row-number 0 column)
735 (pipeglade-out "text_values" "set" row-number 1 value)
736 (pipeglade-out "text_values" "set" row-number 2 color)
737 (pipeglade-out "text_values" "set" row-number 3 (* 4 (parse-integer width :junk-allowed t))))) ;text size
739 (defun put-text-values (vnk nnk station)
740 (let ((row-number 0))
741 (when (vectorp *road-network-chart-configuration*)
742 (loop
743 for style-definition across *road-network-chart-configuration*
745 (when (data-style-textp style-definition)
746 (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))
747 (incf row-number))))
748 (when (vectorp *zeb-chart-configuration*)
749 (loop
750 for style-definition across *zeb-chart-configuration*
752 (when (data-style-textp style-definition)
753 (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))
754 (incf row-number))))))
756 (defun accidents-data (vnk nnk &key
757 (year-min most-negative-fixnum)
758 (year-max most-positive-fixnum))
759 "Return a list of plists containing accident data for the road
760 section between vnk and nnk."
761 (let ((table (intern (db-credentials-table *postgresql-accidents-credentials*))))
762 (with-connection *postgresql-accidents-credentials*
763 (query (:order-by
764 (:select 'nk-station 'fahrtrichtung 'unfalltyp 'unfallkategorie 'alkohol
765 :from table
766 :where (:and (:= 'vnk vnk)
767 (:= 'nnk nnk)
768 (:between 'jahr year-min year-max)))
769 'nk-station 'jahr 'monat 'tag 'stunde 'minuten)
770 :plists))))
772 (defun populate-road-section-dialog ()
773 (with-statusbar-message "populating road section list"
774 (with-spinner "road_section_spinner"
775 (pipeglade-out "road_sections" "clear")
776 (ignore-errors
777 (with-connection *postgresql-road-network-credentials*
778 (let ((sections (sections (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))))
779 (loop
780 for (vnk nnk length) in sections
781 for row-number from 0
783 (add-vnk-nnk-leaf vnk nnk length row-number))))))))
785 (defun update-credentials-dialog ()
786 (with-statusbar-message "initialising credentials"
787 (pipeglade-out "road_network_host" "set_text" (db-credentials-host *postgresql-road-network-credentials*))
788 (pipeglade-out "road_network_port" "set_text" (db-credentials-port *postgresql-road-network-credentials*))
789 (pipeglade-out "road_network_ssl" "set_active" (if (eq (db-credentials-ssl *postgresql-road-network-credentials*) :no) 0 1))
790 (pipeglade-out "road_network_database" "set_text" (db-credentials-database *postgresql-road-network-credentials*))
791 (pipeglade-out "road_network_table" "set_text" (db-credentials-table *postgresql-road-network-credentials*))
792 (pipeglade-out "road_network_user" "set_text" (db-credentials-user *postgresql-road-network-credentials*))
793 (pipeglade-out "road_network_password" "set_text" (db-credentials-password *postgresql-road-network-credentials*))
794 (pipeglade-out "road_network_status" "set_text" "?")
795 (pipeglade-out "zeb_host" "set_text" (db-credentials-host *postgresql-zeb-credentials*))
796 (pipeglade-out "zeb_port" "set_text" (db-credentials-port *postgresql-zeb-credentials*))
797 (pipeglade-out "zeb_ssl" "set_active" (if (eq (db-credentials-ssl *postgresql-zeb-credentials*) :no) 0 1))
798 (pipeglade-out "zeb_database" "set_text" (db-credentials-database *postgresql-zeb-credentials*))
799 (pipeglade-out "zeb_table" "set_text" (db-credentials-table *postgresql-zeb-credentials*))
800 (pipeglade-out "zeb_user" "set_text" (db-credentials-user *postgresql-zeb-credentials*))
801 (pipeglade-out "zeb_password" "set_text" (db-credentials-password *postgresql-zeb-credentials*))
802 (pipeglade-out "zeb_status" "set_text" "?")
803 (pipeglade-out "accidents_host" "set_text" (db-credentials-host *postgresql-accidents-credentials*))
804 (pipeglade-out "accidents_port" "set_text" (db-credentials-port *postgresql-accidents-credentials*))
805 (pipeglade-out "accidents_ssl" "set_active" (if (eq (db-credentials-ssl *postgresql-accidents-credentials*) :no) 0 1))
806 (pipeglade-out "accidents_database" "set_text" (db-credentials-database *postgresql-accidents-credentials*))
807 (pipeglade-out "accidents_table" "set_text" (db-credentials-table *postgresql-accidents-credentials*))
808 (pipeglade-out "accidents_user" "set_text" (db-credentials-user *postgresql-accidents-credentials*))
809 (pipeglade-out "accidents_password" "set_text" (db-credentials-password *postgresql-accidents-credentials*))
810 (pipeglade-out "accidents_status" "set_text" "?")
811 (destructuring-bind (user password) *phoros-credentials*
812 (pipeglade-out "phoros_url" "set_text" *phoros-url*)
813 (pipeglade-out "phoros_user" "set_text" user)
814 (pipeglade-out "phoros_password" "set_text" password)
815 (pipeglade-out "phoros_status" "set_text" "?"))))
817 (defun check-credentials-dialog-statuses ()
818 (with-statusbar-message "checking road network db connection"
819 (pipeglade-out "road_network_status" "set_text" (check-db *postgresql-road-network-credentials*)))
820 (with-statusbar-message "checking zeb db connection"
821 (pipeglade-out "zeb_status" "set_text" (check-db *postgresql-zeb-credentials*)))
822 (with-statusbar-message "checking accidents db connection"
823 (pipeglade-out "accidents_status" "set_text" (check-db *postgresql-accidents-credentials*)))
824 (with-statusbar-message "checking Phoros connection"
825 (pipeglade-out "phoros_status" "set_text" (apply #'check-phoros *phoros-url* *phoros-credentials*))))
827 (defun save-place (place filename-stump)
828 "Save place into a file whose name is based on symbol filename-stump."
829 (let ((cache-file-name (cache-file-name filename-stump)))
830 (ensure-directories-exist cache-file-name)
831 (with-open-file (stream cache-file-name
832 :direction :output
833 :if-exists :supersede)
834 (prin1 place stream))))
836 (defmacro restore-place (place filename-stump &optional default)
837 "Restore place from a file whose name is based on symbol filename-stump."
838 `(with-open-file (stream (cache-file-name ,filename-stump)
839 :direction :input
840 :if-does-not-exist nil)
841 (if stream
842 (setf ,place (read stream))
843 (setf ,place ,default))))
845 (defun save-road-section-selection ()
846 "Save the list of road sections selected for processing."
847 (save-place *road-section-selection* 'road-section-selection))
849 (defun restore-road-section-selection ()
850 (restore-place *road-section-selection* 'road-section-selection))
852 (defun update-road-section-selection ()
853 (with-statusbar-message "restoring road section selection"
854 (with-spinner "road_section_spinner"
855 (ignore-errors
856 (with-connection *postgresql-road-network-credentials*
857 (let ((sections (sections (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))))
858 (loop
859 for row-number from 0 below (length sections)
861 (if (find row-number *road-section-selection*)
862 (pipeglade-out "road_sections" "set" row-number 4 1)
863 (pipeglade-out "road_sections" "set" row-number 4 0))))))
864 (pipeglade-out "road_sections" "scroll"
865 (or (ignore-errors (apply #'min *road-section-selection*))
867 0))))
869 (defun restore-road-section-image-counts ()
870 (with-statusbar-message "restoring road section image counts"
871 (ignore-errors
872 (with-connection *postgresql-road-network-credentials*
873 (let* ((table (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))
874 (sections (sections table)))
875 (loop
876 for (vnk nnk) in sections
877 for row-number from 0
878 do (multiple-value-bind (rearview-image-data rearview-cached-p)
879 (road-section-image-data (provenience-string *phoros-url*) table vnk nnk 10 t :from-cache-only t)
880 (multiple-value-bind (frontview-image-data frontview-cached-p)
881 (road-section-image-data (provenience-string *phoros-url*) table vnk nnk 10 nil :from-cache-only t)
882 (when (and rearview-cached-p frontview-cached-p)
883 (pipeglade-out "road_sections" "set" row-number 3 (+ (length rearview-image-data) (length frontview-image-data))))))))))))
885 (defun save-road-network-credentials (modifiedp)
886 (setf (db-credentials-modifiedp *postgresql-road-network-credentials*) modifiedp)
887 (save-place *postgresql-road-network-credentials* 'road-network-credentials))
889 (defun restore-road-network-credentials ()
890 (restore-place *postgresql-road-network-credentials* 'road-network-credentials))
892 (defun save-zeb-credentials (modifiedp)
893 (setf (db-credentials-modifiedp *postgresql-zeb-credentials*) modifiedp)
894 (save-place *postgresql-zeb-credentials* 'zeb-credentials))
896 (defun restore-zeb-credentials ()
897 (restore-place *postgresql-zeb-credentials* 'zeb-credentials))
899 (defun save-accidents-credentials (modifiedp)
900 (setf (db-credentials-modifiedp *postgresql-accidents-credentials*) modifiedp)
901 (save-place *postgresql-accidents-credentials* 'accidents-credentials))
903 (defun restore-accidents-credentials ()
904 (restore-place *postgresql-accidents-credentials* 'accidents-credentials))
906 (defun save-phoros-credentials ()
907 (save-place *phoros-credentials* 'phoros-credentials)
908 (save-place *phoros-url* 'phoros-url))
910 (defun restore-phoros-credentials ()
911 (restore-place *phoros-credentials* 'phoros-credentials)
912 (restore-place *phoros-url* 'phoros-url))
914 (defun save-road-section ()
915 "Save road-section into cache directory."
916 (save-place *road-section* 'road-section))
918 (defun restore-road-section ()
919 (restore-place *road-section* 'road-section))
921 (defun save-accidents-chart-configuration ()
922 (save-place *accidents-chart-configuration* 'accidents-chart-configuration))
924 (defun save-station (station)
925 "Save position of chart cursor into cache directory."
926 (save-place station 'station))
928 (defun saved-station ()
929 (let ((cache-file-name (cache-file-name 'station))
930 station)
931 (ensure-directories-exist cache-file-name)
932 (with-open-file (stream cache-file-name
933 :direction :input
934 :if-does-not-exist nil)
935 (when stream (setf station (read stream)))
936 (or station 0))))
938 (defun restore-road-network-chart-configuration ()
939 (unless (db-credentials-modifiedp *postgresql-road-network-credentials*)
940 (restore-place *road-network-chart-configuration* 'road-network-chart-configuration)))
942 (defun restore-zeb-chart-configuration ()
943 (unless (db-credentials-modifiedp *postgresql-zeb-credentials*)
944 (restore-place *zeb-chart-configuration* 'zeb-chart-configuration)))
946 (defun restore-accidents-chart-configuration ()
947 (unless (db-credentials-modifiedp *postgresql-accidents-credentials*)
948 (restore-place *accidents-chart-configuration* 'accidents-chart-configuration (list "1" "1999" "2030"))))
950 (defun set-road-section (&key direction)
951 (let* ((table (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))
952 (sections (sections table))
953 (sections-current (position (cdr *road-section*) sections :test #'equal))
954 (selection-current (position sections-current *road-section-selection*)))
955 (cond ((and *road-section-selection* (eq direction :predecessor))
956 (let ((selection-predecessor (ignore-errors (nth (1- selection-current) *road-section-selection*))))
957 (when selection-predecessor
958 (setf *road-section*
959 (cons table (nth selection-predecessor sections))))))
960 ((and *road-section-selection* (eq direction :successor))
961 (let* ((selection-successor (nth (1+ selection-current) *road-section-selection*)))
962 (when selection-successor
963 (setf *road-section*
964 (cons table (nth selection-successor sections))))))
965 ((and *road-section-selection* (eq direction :last))
966 (setf *road-section* (cons table
967 (nth (car (last *road-section-selection*)) sections))))
968 (*road-section-selection*
969 (setf *road-section* (cons table
970 (nth (first *road-section-selection*) sections))))
972 (setf *road-section* nil)))))
974 (let (old-road-section)
975 (defun update-station (&optional station)
976 "If either station is supplied or *road-section* has changed, change station widget in UI. Return nil if nothing has been changed"
977 (cond ((numberp station)
978 (setf old-road-section *road-section*)
979 (pipeglade-out "station_scale" "set_value" station)
980 (save-station station))
981 ((not (and old-road-section
982 (equal (cdr *road-section*) (cdr old-road-section))
983 (equal (string (car *road-section*)) (string (car *road-section*))))) ;comparing uninterned symbols
984 (setf old-road-section *road-section*)
985 (pipeglade-out "station_scale" "set_value" 0)
986 (save-station 0))
988 nil))))
990 (defun check-db (db-credentials &aux result)
991 "Check database connection and presence of table or view table-name.
992 Return a string describing the outcome."
993 (let ((table-name (db-credentials-table db-credentials)))
994 (unless
995 (ignore-errors
996 (with-connection db-credentials
997 (if (or (table-exists-p table-name)
998 (view-exists-p table-name))
999 (setf result "ok")
1000 (setf result "table or view missing"))))
1001 (setf result "connection failure"))
1002 result))
1004 (defun check-phoros (url user-name password)
1005 "Check connection to phoros server. Return a string describing the
1006 outcome."
1007 (let ((*phoros-url* url)
1008 (*phoros-cookies* nil))
1009 (unwind-protect
1010 (handler-case (phoros-login url user-name password)
1011 (usocket:ns-host-not-found-error () "host not found")
1012 (usocket:connection-refused-error () "connection refused")
1013 (error (c) (format nil "~A" c))
1014 (:no-error (result) (if result "ok" "wrong user or password")))
1015 (ignore-errors (phoros-logout)))))
1017 (defun populate-chart-dialog ()
1018 (with-statusbar-message "initialising chart configuration"
1019 (update-chart-dialog-treeview "road_network" *postgresql-road-network-credentials* *road-network-chart-configuration*)
1020 (update-chart-dialog-treeview "zeb" *postgresql-zeb-credentials* *zeb-chart-configuration*)
1021 (update-accidents-chart-dialog)))
1024 (defun update-chart-dialog ()
1025 (with-statusbar-message "updating chart configuration"
1026 (when (db-credentials-modifiedp *postgresql-road-network-credentials*)
1027 (update-chart-dialog-treeview "road_network" *postgresql-road-network-credentials* *road-network-chart-configuration*)
1028 (save-road-network-credentials nil))
1029 (when (db-credentials-modifiedp *postgresql-zeb-credentials*)
1030 (update-chart-dialog-treeview "zeb" *postgresql-zeb-credentials* *zeb-chart-configuration*)
1031 (save-zeb-credentials nil))
1032 (when (db-credentials-modifiedp *postgresql-accidents-credentials*)
1033 (update-accidents-chart-dialog)
1034 (save-accidents-credentials nil))))
1036 (defun update-chart-dialog-treeview (treeview db-credentials chart-configuration)
1037 (with-statusbar-message "updating chart configuration"
1038 (ignore-errors
1039 (with-connection db-credentials
1040 (present-db-columns (table-description (db-credentials-table db-credentials)) treeview chart-configuration)))))
1043 (defun update-accidents-chart-dialog ()
1044 (pipeglade-out "render_accidents" "set_active" (first *accidents-chart-configuration*))
1045 (pipeglade-out "accidents_from" "set_text" (second *accidents-chart-configuration*))
1046 (pipeglade-out "accidents_to" "set_text" (third *accidents-chart-configuration*)))
1048 (defun present-db-columns (columns treeview chart-configuration)
1049 (pipeglade-out treeview "clear")
1050 (loop
1051 for (column-name type) in (sort columns #'string-lessp :key #'car)
1052 for row-number from 0
1054 (let ((selected-column (find column-name chart-configuration :key #'data-style-name :test #'string-equal))
1055 (drawablep (numeric-type-p type)))
1056 (pipeglade-out treeview "set" row-number 0 column-name)
1057 (pipeglade-out treeview "set" row-number 1 type)
1058 (pipeglade-out treeview "set" row-number 2 (or (data-style-width selected-column) 2))
1059 (pipeglade-out treeview "set" row-number 3 (or (data-style-color selected-column) "black"))
1060 (pipeglade-out treeview "set" row-number 4 (or (data-style-dash selected-column) ""))
1061 (pipeglade-out treeview "set" row-number 5 (if (and drawablep (data-style-chartp selected-column)) 1 0))
1062 (pipeglade-out treeview "set" row-number 6 (if (data-style-textp selected-column) 1 0))
1063 (pipeglade-out treeview "set" row-number 7 (if drawablep 1 0))
1064 (pipeglade-out treeview "set_cursor" row-number))) ;tickle initial pipeglade output
1065 (pipeglade-out treeview "set_cursor")
1066 (pipeglade-out treeview "scroll" 0 0))
1068 (defun numeric-type-p (type)
1069 (some #'identity (mapcar (lambda (x) (search x type))
1070 '("float" "double" "int" "numeric" "serial"))))
1072 (defun add-vnk-nnk-leaf (vnk nnk length row-number)
1073 "Put a leaf into road-sections tree."
1074 (pipeglade-out "road_sections" "set" row-number 0 vnk)
1075 (pipeglade-out "road_sections" "set" row-number 1 nnk)
1076 (pipeglade-out "road_sections" "set" row-number 2 length))
1078 (defun prepare-chart ()
1079 "Prepare chart for the road section between vnk and nnk in table in
1080 current database."
1081 (when *road-section*
1082 (destructuring-bind (table vnk nnk road-section-length) *road-section*
1083 (pipeglade-out "ovl_chart" "set_size_request" (+ *chart-tail* road-section-length) (+ *chart-height* *chart-fringe*))
1084 (pipeglade-out "vnk" "set_text" vnk)
1085 (pipeglade-out "nnk" "set_text" nnk)
1086 (pipeglade-out "length" "set_text" road-section-length)
1087 (draw-chart-cursor-scale road-section-length)
1088 (pipeglade-out "station_scale" "set_range" 0 road-section-length)
1089 (setf *road-section* (list table vnk nnk road-section-length))
1090 (save-road-section)
1091 (draw-graphs vnk nnk)
1092 (pipeglade-out "station_scale" "set_value" (saved-station)))))
1094 (defun place-chart-cursor (station)
1095 "Move chart cursor to station."
1096 (when station
1097 (pipeglade-out "chart_cursor" "remove" 2)
1098 (pipeglade-out "chart_cursor" "move_to" 2 station 0)
1099 (pipeglade-out "chart_cursor" "line_to" 2 station (+ *chart-height* *chart-fringe*))
1100 (pipeglade-out "chart_cursor" "stroke" 2)
1101 (pipeglade-out "chart_scroll" "hscroll_to_range" (- station 200) (+ station 200))
1102 (pipeglade-out "chart_road_network_scale" "translate" "=3" station 0)
1103 (pipeglade-out "chart_zeb_scale" "translate" "=3" station 0)))
1105 (defun refresh-chart ()
1106 "Redraw chart."
1107 (when (= (length *road-section*) 4)
1108 (prepare-chart)))
1110 (defun draw-graphs (vnk nnk)
1111 "Draw graphs for the columns in *zeb-chart-configuration* and
1112 *road-network-chart-configuration*. Delete existing graphs first."
1113 (with-statusbar-message "drawing chart"
1114 (with-spinner "chart_spinner"
1115 (pipeglade-out "chart_road_network" "remove" 2)
1116 (pipeglade-out "chart_road_network_scale" "remove" 2)
1117 (pipeglade-out "chart_road_network_scale" "translate" "=3" 0 0)
1118 (pipeglade-out "chart_zeb" "remove" 2)
1119 (pipeglade-out "chart_zeb_scale" "remove" 2)
1120 (pipeglade-out "chart_zeb_scale" "translate" "=3" 0 0)
1121 (let ((scale-position *scale-distance*))
1122 (with-statusbar-message "drawing road-network chart"
1123 (when (vectorp *road-network-chart-configuration*)
1124 (loop
1125 for style-definition across *road-network-chart-configuration*
1127 (when (data-style-chartp style-definition)
1128 (ignore-errors
1129 (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))
1130 (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))
1131 (incf scale-position *scale-distance*))))))
1132 (with-statusbar-message "drawing zeb chart"
1133 (when (vectorp *zeb-chart-configuration*)
1134 (loop
1135 for style-definition across *zeb-chart-configuration*
1137 (when (data-style-chartp style-definition)
1138 (ignore-errors
1139 (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))
1140 (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))
1141 (incf scale-position *scale-distance*)))))))
1142 (pipeglade-out "chart_accidents" "remove" 2)
1143 (ignore-errors
1144 (draw-accidents vnk nnk)))))
1146 (defun draw-graph (chart-data-function chart column vnk nnk color width dash)
1147 (multiple-value-bind (line minimum maximum)
1148 (funcall chart-data-function column vnk nnk *chart-height*)
1149 (let ((line-fragments
1150 (cl-utilities:split-sequence-if #'(lambda (x)
1151 (eq (second x) :null))
1152 line
1153 :remove-empty-subseqs t)))
1154 (pipeglade-out chart "set_source_rgba" 2 color)
1155 (pipeglade-out chart "set_line_width" 2 width)
1156 (pipeglade-out chart "set_dash" 2 dash)
1157 (dolist (line-fragment line-fragments)
1158 (pipeglade-out chart "move_to" 2 (first (car line-fragment)) (second (car line-fragment)))
1159 (dolist (line-vertex (cdr line-fragment))
1160 (pipeglade-out chart "line_to" 2 (first line-vertex) (second line-vertex)))
1161 (pipeglade-out chart "stroke" 2)))))
1163 (defun draw-scale (position chart-data-function chart column vnk nnk color width dash)
1164 (multiple-value-bind (line minimum maximum)
1165 (funcall chart-data-function column vnk nnk *chart-height*)
1166 (pipeglade-out chart "set_source_rgba" 2 color)
1167 (pipeglade-out chart "set_line_width" 2 width)
1168 (pipeglade-out chart "move_to" 2 position 0)
1169 (pipeglade-out chart "line_to" 2 position *chart-height*)
1170 (dolist (tick (axis-ticks minimum maximum 5 *chart-height* t))
1171 (pipeglade-out chart "move_to" 2 position (format nil "~F" (second tick)))
1172 (pipeglade-out chart "rel_line_to" 2 (* 2 (parse-integer width)) 0)
1173 (pipeglade-out chart "move_to" 2 position (format nil "~F" (second tick)))
1174 (pipeglade-out chart "rel_move_to" 2 (- (parse-integer width)) 0)
1175 (pipeglade-out chart "rel_move_for" 2 "e" (first tick))
1176 (pipeglade-out chart "show_text" 2 (first tick)))
1177 (pipeglade-out chart "move_to" 2 position (format nil "~F" (+ *chart-height* (/ *chart-fringe* 2))))
1178 (pipeglade-out chart "rel_move_for" 2 "c" column)
1179 (pipeglade-out chart "show_text" 2 column)
1180 (pipeglade-out chart "stroke" 2)))
1182 (defun draw-chart-cursor-scale (length)
1183 (let ((y-position (+ *chart-height* *chart-fringe*))
1184 (number-of-ticks (round length 100)))
1185 (pipeglade-out "chart_cursor" "remove" 4)
1186 (dolist (tick (axis-ticks 0 length number-of-ticks length nil))
1187 (pipeglade-out "chart_cursor" "move_to" 4 (second tick) y-position)
1188 (pipeglade-out "chart_cursor" "line_to" 4 (second tick) (- y-position 3))
1189 (pipeglade-out "chart_cursor" "rel_move_for" 4 "s" (first tick))
1190 (pipeglade-out "chart_cursor" "show_text" 4 (first tick)))
1191 (pipeglade-out "chart_cursor" "stroke" 4)))
1193 (defun axis-ticks (minimum maximum n chart-size reversep)
1194 (let ((range (- maximum minimum)))
1195 (if (zerop range)
1196 (list (list (format nil "~F" minimum) (/ chart-size 2)))
1197 (let* ((a (if reversep
1198 (- (/ chart-size range))
1199 (/ chart-size range)))
1200 (b (if reversep
1201 (* a maximum)
1202 (- (* a maximum) chart-size)))
1203 (min-step (/ range (1+ n)))
1204 (max-step (/ range (1- n)))
1205 (max-exp (log max-step 10))
1206 (int-exp (floor max-exp))
1207 (norm-min (floor (/ min-step (expt 10 int-exp))))
1208 (norm-max (floor (/ max-step (expt 10 int-exp))))
1209 (norm (cond
1210 ((or (= norm-min 1) (= norm-max 1))
1212 ((or (<= norm-min 4 norm-max) (<= norm-min 5 norm-max) (<= norm-min 6 norm-max))
1214 ((or (<= norm-min 2) (<= norm-min 3 norm-max))
1215 2.5)
1216 ((<= 7 norm-max)
1219 norm-max))) ;can't happen
1220 (step (* norm (expt 10 int-exp)))
1221 (start (- minimum (nth-value 1 (fceiling minimum step)))))
1222 (loop
1223 for i from start to maximum by step
1224 collect (list (if (minusp int-exp)
1225 (format nil "~,VF" (- int-exp) i)
1226 (format nil "~A" (round i)))
1227 (- (* a i) b)))))))
1229 (defun draw-accidents (vnk nnk)
1230 (when (string-equal (first *accidents-chart-configuration*) "1")
1231 (let* ((year-min (second *accidents-chart-configuration*))
1232 (year-max (third *accidents-chart-configuration*))
1233 (accidents (accidents-data vnk nnk :year-min year-min :year-max year-max))
1234 (current-station -1)
1235 (zeroth-position -1)
1236 y1-position
1237 y2-position)
1238 (dolist (accident accidents)
1239 (unless (= current-station (getf accident :nk-station))
1240 (setf y1-position (- *chart-height* zeroth-position))
1241 (setf y2-position zeroth-position)
1242 (setf y0-position (+ (/ *chart-height* 2) zeroth-position)))
1243 (setf current-station (getf accident :nk-station))
1244 (cond ((= 1 (getf accident :fahrtrichtung))
1245 (draw-accident accident (decf y1-position 10)))
1246 ((= 2 (getf accident :fahrtrichtung))
1247 (draw-accident accident (incf y2-position 10)))
1249 (draw-accident accident (incf y0-position 10))))))))
1251 (defun draw-accident (accident y-position)
1252 "Put graphical representation of accident on chart."
1253 (destructuring-bind (&key nk-station fahrtrichtung unfalltyp unfallkategorie alkohol)
1254 accident
1255 (when (and (numberp alkohol) (plusp alkohol)) (draw-triangle nk-station y-position "lightblue"))
1256 (case unfallkategorie
1257 (1 (draw-rectangle nk-station y-position 10 "black")
1258 (draw-circle nk-station y-position 8 (accident-type-color unfalltyp)))
1259 (2 (draw-circle nk-station y-position 8 (accident-type-color unfalltyp)))
1260 (3 (draw-circle nk-station y-position 6 (accident-type-color unfalltyp)))
1261 (4 (draw-circle nk-station y-position 6 "white")
1262 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1263 (5 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1264 (6 (draw-triangle nk-station y-position "lightblue")
1265 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1266 (t (draw-circle nk-station y-position 4 (accident-type-color unfalltyp))))))
1268 (defun draw-circle (x y diameter color)
1269 (pipeglade-out "chart_accidents" "set_source_rgba" 2 "black")
1270 (pipeglade-out "chart_accidents" "arc" 2 x y (/ diameter 2) 0 360)
1271 (pipeglade-out "chart_accidents" "stroke_preserve" 2)
1272 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1273 (pipeglade-out "chart_accidents" "fill" 2))
1275 (defun draw-rectangle (x y diameter color)
1276 (let ((radius (/ diameter 2)))
1277 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1278 (pipeglade-out "chart_accidents" "rectangle" 2 (- x radius) (- y radius) diameter diameter)
1279 (pipeglade-out "chart_accidents" "fill" 2)))
1281 (defun draw-triangle (x y color)
1282 (pipeglade-out "chart_accidents" "set_source_rgba" 2 "black")
1283 (pipeglade-out "chart_accidents" "move_to" 2 (- x 3) (- y 6))
1284 (pipeglade-out "chart_accidents" "line_to" 2 (+ x 3) (- y 6))
1285 (pipeglade-out "chart_accidents" "line_to" 2 x (+ y 9))
1286 (pipeglade-out "chart_accidents" "close_path" 2)
1287 (pipeglade-out "chart_accidents" "stroke_preserve" 2)
1288 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1289 (pipeglade-out "chart_accidents" "fill" 2))
1291 (defun accident-type-color (accident-type)
1292 (case accident-type
1293 (1 "green")
1294 (2 "yellow")
1295 (3 "red")
1296 (4 "white")
1297 (5 "lightblue")
1298 (6 "orange")
1299 (7 "black")
1300 (t "darkblue")))
1302 (defun jump-to-station (station &key synchronous)
1303 (when *cruise-control-thread*
1304 (unless synchronous
1305 (return-from jump-to-station)) ;ignore effect of updating station_scale while cruise-controlling
1306 (pipeglade-out "station_scale" "set_value" station))
1307 (save-station station)
1308 (and (bt:threadp *jump-to-station-thread*) (bt:thread-alive-p *jump-to-station-thread*) (bt:destroy-thread *jump-to-station-thread*))
1309 (unless
1310 (ignore-errors
1311 (setf *jump-to-station-thread*
1312 (bt:make-thread
1313 (lambda ()
1314 (let ((table (first *road-section*))
1315 (vnk (second *road-section*))
1316 (nnk (third *road-section*)))
1317 (pipeglade-out "station" "set_text" station)
1318 (place-chart-cursor station)
1319 (if *show-rear-view-p*
1320 (ignore-errors (put-image :vnk vnk :nnk nnk :station station :step 10 :rear-view-p t))
1321 (progn
1322 (pipeglade-out "draw_rearview" "remove" 2)
1323 (pipeglade-out "img_rearview" "set_from_file")))
1324 (if *show-front-view-p*
1325 (ignore-errors (put-image :vnk vnk :nnk nnk :station station :step 10 :rear-view-p nil))
1326 (progn
1327 (pipeglade-out "draw_frontview" "remove" 2)
1328 (pipeglade-out "img_frontview" "set_from_file")))
1329 (put-text-values vnk nnk station)))))
1330 (when synchronous
1331 (bt:join-thread *jump-to-station-thread*)
1332 (and (bt:threadp *rear-view-image-thread*) (bt:join-thread *rear-view-image-thread*))
1333 (and (bt:threadp *front-view-image-thread*) (bt:join-thread *front-view-image-thread*)))
1335 (clear-main-window)))
1337 (defun cruise-control (&key backwardp)
1338 (let ((road-section-length (fourth *road-section*)))
1339 (setf *cruise-control-thread*
1340 (bt:make-thread
1341 (lambda ()
1342 (loop
1344 (jump-to-station (+ (if backwardp (- *big-step*) *big-step*)
1345 (saved-station)) :synchronous t)
1346 (jump-to-station (+ (if backwardp (- *big-step*) *big-step*)
1347 (saved-station)) :synchronous t)
1348 while (<= (+ 0 *big-step*) (saved-station) (- road-section-length *big-step*))))))))
1350 (defun stop-cruise-control ()
1351 (and (bt:threadp *cruise-control-thread*) (bt:thread-alive-p *cruise-control-thread*) (bt:destroy-thread *cruise-control-thread*))
1352 (setf *cruise-control-thread* nil))
1354 (defun put-image (&key vnk nnk station step rear-view-p)
1355 "Put an image along with a labelled station marker on screen."
1356 (with-connection *postgresql-road-network-credentials*
1357 (setf station (or station 0))
1358 (let* ((table (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))
1359 (point-radius 5)
1360 (image-widget (if rear-view-p "img_rearview" "img_frontview"))
1361 (drawing-widget (if rear-view-p "draw_rearview" "draw_frontview"))
1362 (spinner-widget (if rear-view-p "spinner_rearview" "spinner_frontview"))
1363 (time-widget (if rear-view-p "rear_view_time" "front_view_time"))
1364 (global-point-coordinates
1365 (subseq (all-stations table vnk nnk)
1366 (min (length (all-stations table vnk nnk)) station)
1367 (min (length (all-stations table vnk nnk)) (+ station 4))))
1368 (image-data-alist
1369 (get-image-data-alist (road-section-image-data (provenience-string *phoros-url*) table vnk nnk step rear-view-p)
1370 station
1371 step))
1372 (image-arrow-coordinates
1373 (loop
1374 for i across global-point-coordinates
1375 append (image-point-coordinates image-data-alist i)))
1376 (image-label-coordinates (ignore-errors
1377 (list (- (first image-arrow-coordinates) point-radius)
1378 (- (second image-arrow-coordinates) point-radius))))
1379 (image-data (get-image-data (road-section-image-data (provenience-string *phoros-url*) table vnk nnk step rear-view-p) station step)))
1380 (if image-data
1381 (progn
1382 (unless (image-launched-p image-data rear-view-p)
1383 (if rear-view-p
1384 (and (bt:threadp *rear-view-image-thread*) (bt:thread-alive-p *rear-view-image-thread*) (bt:destroy-thread *rear-view-image-thread*))
1385 (and (bt:threadp *front-view-image-thread*) (bt:thread-alive-p *front-view-image-thread*) (bt:destroy-thread *front-view-image-thread*)))
1386 (let ((thread
1387 (bt:make-thread (lambda ()
1388 (with-spinner spinner-widget
1389 (remember-image-being-launched image-data rear-view-p)
1390 (let ((image-filename (ignore-errors
1391 (when image-data (namestring (download-image image-data))))))
1392 (if image-filename
1393 (pipeglade-out image-widget "set_from_file" image-filename)
1394 (pipeglade-out image-widget "set_from_file" "public_html/phoros-logo-background.png"))))))))
1395 (if rear-view-p
1396 (setf *rear-view-image-thread* thread)
1397 (setf *front-view-image-thread* thread))))
1398 (pipeglade-out time-widget "set_text" (iso-time (image-data-trigger-time image-data)))
1399 (pipeglade-out drawing-widget "remove" 2)
1400 (when image-arrow-coordinates
1401 (pipeglade-out drawing-widget "move_to" 2 (first image-arrow-coordinates) (second image-arrow-coordinates))
1402 (pipeglade-out drawing-widget "line_to" 2 (first (last image-arrow-coordinates 2)) (second (last image-arrow-coordinates 2)))
1403 (pipeglade-out drawing-widget "stroke" 2)
1404 (pipeglade-out drawing-widget "arc" 2 (first image-arrow-coordinates) (second image-arrow-coordinates) point-radius 0 360)
1405 (pipeglade-out drawing-widget "stroke" 2)
1406 (pipeglade-out drawing-widget "move_to" 2 (first image-label-coordinates) (second image-label-coordinates))
1407 (pipeglade-out drawing-widget "rel_move_for" 2 "se" station)
1408 (pipeglade-out drawing-widget "show_text" 2 station)))
1409 (progn
1410 (pipeglade-out image-widget "set_from_file" "public_html/phoros-logo-background.png")
1411 (pipeglade-out time-widget "set_text")
1412 (pipeglade-out drawing-widget "remove" 2))))))
1414 (defun iso-time (time)
1415 (multiple-value-bind (seconds deciseconds)
1416 (floor time)
1417 (multiple-value-bind (second minute hour date month year day daylight-p zone)
1418 (decode-universal-time seconds)
1419 (format nil "~D-~2,'0D-~2,'0D\\n~2,'0D:~2,'0D:~2,'0D~3,3FZ" year month date hour minute second deciseconds))))
1421 (defun image-point-coordinates (image-data-alist global-point-coordinates)
1422 "Return a list (m n) of image coordinates representing
1423 global-point-coordinates in the image described in image-data-alist
1424 but scaled to fit into *image-size*."
1425 (ignore-errors
1426 (convert-image-coordinates
1427 (photogrammetry :reprojection
1428 image-data-alist
1429 (pairlis '(:x-global :y-global :z-global)
1430 (proj:cs2cs
1431 (list
1432 (proj:degrees-to-radians
1433 (coordinates-longitude global-point-coordinates))
1434 (proj:degrees-to-radians
1435 (coordinates-latitude global-point-coordinates))
1436 (coordinates-ellipsoid-height global-point-coordinates))
1437 :destination-cs (cdr (assoc :cartesian-system image-data-alist)))))
1438 image-data-alist)))
1440 (defun in-image-p (m n)
1441 "Check if m, n lay inside *image-size*."
1442 (and m n (<= 0 m (first *image-size*)) (<= 0 n (second *image-size*))))
1444 (defun-cached sections (table)
1445 "Return list of distinct pairs of vnk, nnk found in table in
1446 current database."
1447 (ignore-errors
1448 (query (:order-by (:select 'vnk 'nnk (:max 'nk-station)
1449 :from (db-credentials-table *postgresql-road-section-credentials*)
1450 :where (:and (:not-null 'vnk) (:not-null 'nnk))
1451 :group-by 'vnk 'nnk)
1452 'vnk 'nnk))))
1454 (defun stations (table vnk nnk &optional (step 1))
1455 "Return a list of plists of :longitude, :latitude,
1456 :ellipsoid-height, :station, :azimuth of stations step metres apart
1457 between vnk and nnk."
1458 (let ((stations
1459 (query
1460 (:order-by
1461 (:select (:as (:st_x 't1.the-geom) 'longitude)
1462 (:as (:st_y 't1.the-geom) 'latitude)
1463 (:as (:st_z 't1.the-geom) 'ellipsoid-height)
1464 (:as 't1.nk-station 'station)
1465 (:as (:st_azimuth 't1.the-geom 't2.the-geom) 'azimuth)
1466 :from (:as table 't1)
1467 :left-join (:as table 't2)
1468 :on (:and (:= 't1.nk-station (:- 't2.nk-station 1))
1469 (:= 't2.vnk vnk)
1470 (:= 't2.nnk nnk))
1471 :where (:and (:= 't1.vnk vnk)
1472 (:= 't1.nnk nnk)
1473 (:= 0 (:% 't1.nk-station step))))
1474 't1.nk-station)
1475 :plists)))
1476 (setf
1477 (getf (nth (- (length stations) 1) stations) :azimuth)
1478 (getf (nth (- (length stations) 2) stations) :azimuth))
1479 stations))
1481 (defun-cached all-stations (table vnk nnk)
1482 "Return a vector of coordinates of all points between vnk and nnk,
1483 station (in metres) being the vector index."
1484 (let* ((stations (stations table vnk nnk))
1485 (result (make-array (list (1+ (getf (first (last stations)) :station)))
1486 :initial-element nil)))
1487 (loop
1488 for i in stations
1489 do (destructuring-bind (&key longitude latitude ellipsoid-height station azimuth)
1491 (setf (svref result station)
1492 (make-coordinates :longitude longitude
1493 :latitude latitude
1494 :ellipsoid-height ellipsoid-height
1495 :azimuth azimuth))))
1496 result))
1498 (defun-cached road-section-image-data (provenience-string table vnk nnk step rear-view-p)
1499 "Return a list of instances of image data corresponding to stations,
1500 which are step metres apart, found in table in current database.
1501 provenience-string only serves as a marker of the provenience of image
1502 data once cached."
1503 (remove nil ;; (mapcar #'(lambda (x)
1504 ;; (apply #'image-data :rear-view-p rear-view-p x))
1505 ;; (stations table vnk nnk step))
1506 (loop
1507 with azimuth-fallback = nil
1508 for station in (stations table vnk nnk step)
1509 when (not (eq (getf station :azimuth) :null))
1510 do (setf azimuth-fallback (getf station :azimuth))
1511 and collect (apply #'image-data :rear-view-p rear-view-p station)
1513 when (and azimuth-fallback
1514 (eq (getf station :azimuth) :null))
1515 do (setf (getf station :azimuth) azimuth-fallback)
1516 and collect (apply #'image-data :rear-view-p rear-view-p station))))
1518 (defun provenience-string (url)
1519 "Turn url recognisably into something suitable as part of a file
1520 name."
1521 (let ((parsed-url (puri:parse-uri url)))
1522 (format nil "~A_~A~{_~A~}"
1523 (puri:uri-host parsed-url)
1524 (puri:uri-port parsed-url)
1525 (cl-utilities:split-sequence
1526 #\/ (puri:uri-path parsed-url) :remove-empty-subseqs t))))
1529 (defun cache-file-name (kind &rest args)
1530 "Return pathname for a cache file distinguishable by kind and args."
1531 (make-pathname :directory *cache-dir*
1532 :name (format nil "~{~:[f~;~:*~(~A~)~]_~}~A"
1533 args
1534 *fasttrack-version*)
1535 :type (string-downcase kind)))
1537 (defun cache-images (road-section-image-data)
1538 "Download images described in road-section-image-data into their
1539 canonical places."
1540 (loop
1541 for i in road-section-image-data
1542 do (download-image i)))
1544 (defun get-image-data (road-section-image-data station step)
1545 "Return image data for the image near station."
1546 (find (* step (round station step)) road-section-image-data
1547 :key #'image-data-station
1548 :test #'=))
1550 (defun get-image-data-alist (road-section-image-data station step)
1551 "Return as an alist data for the image near station."
1552 (image-data-alist (get-image-data road-section-image-data station step)))
1554 (defun image-data (&key longitude latitude ellipsoid-height station azimuth rear-view-p)
1555 "Get from Phoros server image data for location near longitude,
1556 latitude."
1557 (ignore-errors
1558 (let* ((coordinates (make-coordinates :longitude longitude
1559 :latitude latitude
1560 :ellipsoid-height ellipsoid-height
1561 :azimuth azimuth))
1562 (image-data (phoros-nearest-image-data coordinates rear-view-p)))
1563 (when (image-data-p image-data)
1564 (setf (image-data-station image-data) station)
1565 (setf (image-data-station-coordinates image-data) coordinates)
1566 image-data))))
1568 (define-condition phoros-server-error (error)
1569 ((body :reader body :initarg :body)
1570 (status-code :reader status-code :initarg :status-code)
1571 (headers :reader headers :initarg :headers)
1572 (url :reader url :initarg :url)
1573 (reason-phrase :reader reason-phrase :initarg :reason-phrase))
1574 (:report (lambda (condition stream)
1575 (format stream "Can't connect to Phoros server: ~A (~D)"
1576 (reason-phrase condition) (status-code condition)))))
1578 (defun phoros-lib-url (canonical-url suffix)
1579 "Replace last path element of canonical-url by lib/<suffix>."
1580 (let* ((parsed-canonical-url (puri:parse-uri canonical-url))
1581 (old-path (puri:uri-parsed-path parsed-canonical-url))
1582 (new-path (append (butlast old-path) (list "lib" suffix)))
1583 (new-url (puri:copy-uri parsed-canonical-url)))
1584 (setf (puri:uri-parsed-path new-url) new-path)
1585 new-url))
1587 (defun phoros-login (url user-name user-password)
1588 "Log into Phoros server; return T if successful. Try logging out
1589 first."
1590 ;; (setf *phoros-url* url)
1591 (setf drakma:*allow-dotless-cookie-domains-p* t)
1592 (pushnew (cons "application" "json") drakma:*text-content-types* :test #'equal)
1593 (ignore-errors (phoros-logout))
1594 (setf *phoros-cookies* (make-instance 'drakma:cookie-jar))
1595 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1596 (drakma:http-request (puri:parse-uri url) :cookie-jar *phoros-cookies*)
1597 (declare (ignore stream must-close))
1598 (assert (= status-code 200) ()
1599 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1600 (multiple-value-bind (body status-code headers authenticate-url stream must-close reason-phrase)
1601 (drakma:http-request (phoros-lib-url url "authenticate")
1602 :cookie-jar *phoros-cookies*
1603 :form-data t
1604 :method :post
1605 :parameters (pairlis '("user-name" "user-password")
1606 (list user-name user-password)))
1607 (declare (ignore stream must-close))
1608 (assert (< status-code 400) ()
1609 'phoros-server-error :body body :status-code status-code :headers headers :url authenticate-url :reason-phrase reason-phrase)
1610 (let ((body-strings (cl-utilities:split-sequence #\Space (substitute-if-not #\Space #'alphanumericp body))))
1611 (and (not (find "Rejected" body-strings :test #'string=))
1612 (not (find "Retry" body-strings :test #'string=))
1613 (= status-code 200)))))) ;should be 302 (?)
1615 (defun phoros-logout ()
1616 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1617 (drakma:http-request (phoros-lib-url *phoros-url* "logout"))
1618 (declare (ignore stream must-close))
1619 (assert (= status-code 200) ()
1620 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)))
1622 (defun run-phoros-browser ()
1623 (when *road-section*
1624 (with-statusbar-message "calling browser synchronously"
1625 (destructuring-bind (table vnk nnk road-section-length)
1626 *road-section*
1627 (let ((current-coordinates (svref (all-stations table vnk nnk) (saved-station))))
1628 (uiop:run-program (format nil "firefox '~A/lib/set-cursor?bbox=~F,~F,~F,~F&longitude=~F&latitude=~F'"
1629 *phoros-url*
1630 (- (coordinates-longitude current-coordinates) .02)
1631 (- (coordinates-latitude current-coordinates) .01)
1632 (+ (coordinates-longitude current-coordinates) .02)
1633 (+ (coordinates-latitude current-coordinates) .01)
1634 (coordinates-longitude current-coordinates)
1635 (coordinates-latitude current-coordinates)
1637 (uiop:run-program (format nil "firefox '~A'" *phoros-url*)))))))
1640 (defun heading (azimuth rear-view-p)
1641 "Return as a string the one of east, west, north, south which best
1642 describes azimuth."
1643 (cond ((<= (* 1/4 pi) azimuth (* 3/4 pi)) (if rear-view-p "west" "east"))
1644 ((<= (* 3/4 pi) azimuth (* 5/4 pi)) (if rear-view-p "north" "south"))
1645 ((<= (* 5/4 pi) azimuth (* 7/4 pi)) (if rear-view-p "east" "west"))
1646 ((or (<= (* 5/4 pi) azimuth pi) (<= 0 (* 1/4 pi))) (if rear-view-p "south" "north"))))
1648 (defun phoros-nearest-image-data (coordinates rear-view-p)
1649 "Return a set of image-data."
1650 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1651 (drakma:http-request (phoros-lib-url *phoros-url* "nearest-image-data")
1652 :cookie-jar *phoros-cookies*
1653 :method :post
1654 :content-type "text/plain; charset=UTF-8"
1655 :content (json:encode-json-plist-to-string (list :longitude (coordinates-longitude coordinates)
1656 :latitude (coordinates-latitude coordinates)
1657 :zoom 20
1658 :count 1
1659 :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
1660 (declare (ignore stream must-close))
1661 (assert (= status-code 200) ()
1662 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1663 (unless (string-equal body "null")
1664 (apply #'make-image-data :allow-other-keys t
1665 (plist-from-alist
1666 (car (json:decode-json-from-string body)))))))
1668 (defun download-file (url path)
1669 "Unless already there, store content from url under path. Return
1670 nil if nothing needed storing."
1671 (ensure-directories-exist path)
1672 (with-open-file (file-stream path :direction :output
1673 :element-type 'unsigned-byte
1674 :if-exists nil)
1675 (when file-stream
1676 (multiple-value-bind
1677 (body status-code headers url stream must-close reason-phrase)
1678 (drakma:http-request url
1679 :cookie-jar *phoros-cookies*
1680 :method :get)
1681 (declare (ignore stream must-close))
1682 (setf *t* url)
1683 (assert (= status-code 200) ()
1684 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1685 (write-sequence body file-stream)
1686 reason-phrase))))
1688 (defun download-image (image-data)
1689 "If not already there, download a png image, shrink it, convert it
1690 into jpg, and store it under the cache path. Return that path."
1691 (multiple-value-bind (url origin-path destination-path)
1692 (image-url image-data)
1693 (unless (probe-file destination-path)
1694 (download-file url origin-path)
1695 (apply #'convert-image-file origin-path destination-path *image-size*)
1696 (delete-file origin-path))
1697 destination-path))
1699 (defun image-launched-p (image-data rear-view-p)
1700 "Check if the image belonging to image-data is the current image."
1701 (multiple-value-bind (url origin-path destination-path)
1702 (image-url image-data)
1703 (let ((remembered-image (if rear-view-p
1704 *rear-view-image-path*
1705 *front-view-image-path*)))
1706 (when (and destination-path remembered-image)
1707 (string= (namestring destination-path) (namestring remembered-image))))))
1709 (defun remember-image-being-launched (image-data rear-view-p)
1710 (multiple-value-bind (url origin-path destination-path)
1711 (image-url image-data)
1712 (if rear-view-p
1713 (setf *rear-view-image-path* destination-path)
1714 (setf *front-view-image-path* destination-path))))
1716 (defun forget-images-being-launched ()
1717 (setf *rear-view-image-path* "")
1718 (setf *front-view-image-path* ""))
1720 (defun image-data-alist (image-data)
1721 "Return an alist representation of image-data."
1722 (when image-data
1723 (loop
1724 for i in (append (mapcar #'ensure-hyphen-before-digit *aggregate-view-columns*) '(station station-coordinates))
1725 collect (intern (string i) 'keyword) into keys
1726 collect (funcall (intern (concatenate 'string (string 'image-data-)
1727 (string i)))
1728 image-data)
1729 into values
1730 finally (return (pairlis keys values)))))
1732 (defun plist-from-alist (alist)
1733 (loop
1734 for (key . value) in alist
1735 collect key
1736 collect value))
1738 (defun image-url (image-data)
1739 "Return an image URL made from ingredients found in image-data, the
1740 corresponding cache path, and the corresponding cache path for the
1741 shrunk image."
1742 (let* ((path
1743 (format nil "~A/~A/~A/~D.png"
1744 (puri:uri-path (phoros-lib-url *phoros-url* "photo"))
1745 (image-data-directory image-data)
1746 (image-data-filename image-data)
1747 (image-data-byte-position image-data)))
1748 (query
1749 (format nil "mounting-angle=~D~
1750 &bayer-pattern=~{~D~#^,~}~
1751 &color-raiser=~{~D~#^,~}"
1752 (image-data-mounting-angle image-data)
1753 (map 'list #'identity (image-data-bayer-pattern image-data))
1754 (map 'list #'identity (image-data-color-raiser image-data))))
1755 (url (puri:copy-uri (puri:parse-uri *phoros-url*) :path path :query query))
1756 (host (puri:uri-host url))
1757 (port (puri:uri-port url))
1758 (cache-directory (append *cache-dir*
1759 (list (format nil "~A_~D" host port))
1760 (cdr (pathname-directory (puri:uri-path url)))))
1761 (cache-name (pathname-name (puri:uri-path url)))
1762 (cache-type (pathname-type (puri:uri-path url))))
1763 (values url
1764 (make-pathname :directory cache-directory
1765 :name cache-name
1766 :type cache-type)
1767 (make-pathname :directory cache-directory
1768 :name cache-name
1769 :type "jpg"))))
1771 (defun convert-image-file (origin-file destination-file width height)
1772 "Convert origin-file into destination-file of a maximum size of
1773 width x height."
1774 (lisp-magick-wand:with-magick-wand (wand :load (namestring origin-file))
1775 (let ((a (/ (lisp-magick-wand:get-image-width wand)
1776 (lisp-magick-wand:get-image-height wand))))
1777 (if (> a (/ width height))
1778 (lisp-magick-wand:scale-image wand width (truncate (/ width a)))
1779 (lisp-magick-wand:scale-image wand (truncate (* a height)) height)))
1780 (lisp-magick-wand:write-image wand (namestring destination-file))))
1782 (defun convert-image-coordinates (original-coordinates-alist image-data-alist)
1783 "Convert image coordinates from original-coordinates-alist for the
1784 image in image-data-alist into a list of coordinates for that image
1785 scaled and centered to *image-size*."
1786 (let* ((original-m (cdr (assoc :m original-coordinates-alist)))
1787 (original-n (cdr (assoc :n original-coordinates-alist)))
1788 (original-width (cdr (assoc :sensor-width-pix image-data-alist)))
1789 (original-height (cdr (assoc :sensor-height-pix image-data-alist)))
1790 (new-width (first *image-size*))
1791 (new-height (second *image-size*))
1792 (scaling-factor (min (/ new-width original-width) (/ new-height original-height)))
1793 (new-m-offset (/ (- new-width (* original-width scaling-factor)) 2))
1794 (new-n-offset (/ (- new-height (* original-height scaling-factor)) 2))
1795 (new-m (+ (* original-m scaling-factor) new-m-offset))
1796 (new-n (- new-height ;flip n
1797 (+ (* original-n scaling-factor) new-n-offset))))
1798 (mapcar #'round (list new-m new-n))))