Include fasttrack in binary tarball
[phoros.git] / fasttrack.lisp
blob81d3585eb524653d54177ee483141ba2b354e51a
1 ;;; PHOROS -- Photogrammetric Road Survey
2 ;;; Copyright (C) 2012 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 (print (list "Pre: sect select pred-select *road-section*" sections-current selection-current selection-predecessor *road-section*))))
957 ((and *road-section-selection* (eq direction :successor))
958 (let* ((selection-successor (nth (1+ selection-current) *road-section-selection*)))
959 (when selection-successor
960 (setf *road-section*
961 (cons table (nth selection-successor sections))))
962 (print (list "Suc: sect select succ-select *road-section*" sections-current selection-current selection-successor *road-section*))))
963 ((and *road-section-selection* (eq direction :last))
964 (setf *road-section* (cons table
965 (nth (car (last *road-section-selection*)) sections)))
966 (print (list "Last: sect select *road-section*" sections-current selection-current *road-section*)))
967 (*road-section-selection*
968 (setf *road-section* (cons table
969 (nth (first *road-section-selection*) sections)))
970 (print (list "Manu: sect select *road-section*" sections-current selection-current *road-section*)))
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 (print (list "ROAD NETWORK GRAPH" style-definition))
1130 (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))
1131 (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))
1132 (incf scale-position *scale-distance*))))))
1133 (with-statusbar-message "drawing zeb chart"
1134 (when (vectorp *zeb-chart-configuration*)
1135 (loop
1136 for style-definition across *zeb-chart-configuration*
1138 (when (data-style-chartp style-definition)
1139 (ignore-errors
1140 (print (list "ZEB GRAPH" style-definition))
1141 (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))
1142 (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))
1143 (incf scale-position *scale-distance*)))))))
1144 (pipeglade-out "chart_accidents" "remove" 2)
1145 (ignore-errors
1146 (print "ACCIDENTS")
1147 (draw-accidents vnk nnk)))))
1149 (defun draw-graph (chart-data-function chart column vnk nnk color width dash)
1150 (multiple-value-bind (line minimum maximum)
1151 (funcall chart-data-function column vnk nnk *chart-height*)
1152 (let ((line-fragments
1153 (cl-utilities:split-sequence-if #'(lambda (x)
1154 (eq (second x) :null))
1155 line
1156 :remove-empty-subseqs t)))
1157 (pipeglade-out chart "set_source_rgba" 2 color)
1158 (pipeglade-out chart "set_line_width" 2 width)
1159 (pipeglade-out chart "set_dash" 2 dash)
1160 (dolist (line-fragment line-fragments)
1161 (pipeglade-out chart "move_to" 2 (first (car line-fragment)) (second (car line-fragment)))
1162 (dolist (line-vertex (cdr line-fragment))
1163 (pipeglade-out chart "line_to" 2 (first line-vertex) (second line-vertex)))
1164 (pipeglade-out chart "stroke" 2)))))
1166 (defun draw-scale (position chart-data-function chart column vnk nnk color width dash)
1167 (multiple-value-bind (line minimum maximum)
1168 (funcall chart-data-function column vnk nnk *chart-height*)
1169 (pipeglade-out chart "set_source_rgba" 2 color)
1170 (pipeglade-out chart "set_line_width" 2 width)
1171 (pipeglade-out chart "move_to" 2 position 0)
1172 (pipeglade-out chart "line_to" 2 position *chart-height*)
1173 (dolist (tick (axis-ticks minimum maximum 5 *chart-height* t))
1174 (pipeglade-out chart "move_to" 2 position (format nil "~F" (second tick)))
1175 (pipeglade-out chart "rel_line_to" 2 (* 2 (parse-integer width)) 0)
1176 (pipeglade-out chart "move_to" 2 position (format nil "~F" (second tick)))
1177 (pipeglade-out chart "rel_move_to" 2 (- (parse-integer width)) 0)
1178 (pipeglade-out chart "rel_move_for" 2 "e" (first tick))
1179 (pipeglade-out chart "show_text" 2 (first tick)))
1180 (pipeglade-out chart "move_to" 2 position (format nil "~F" (+ *chart-height* (/ *chart-fringe* 2))))
1181 (pipeglade-out chart "rel_move_for" 2 "c" column)
1182 (pipeglade-out chart "show_text" 2 column)
1183 (pipeglade-out chart "stroke" 2)))
1185 (defun draw-chart-cursor-scale (length)
1186 (let ((y-position (+ *chart-height* *chart-fringe*))
1187 (number-of-ticks (round length 100)))
1188 (pipeglade-out "chart_cursor" "remove" 4)
1189 (dolist (tick (axis-ticks 0 length number-of-ticks length nil))
1190 (pipeglade-out "chart_cursor" "move_to" 4 (second tick) y-position)
1191 (pipeglade-out "chart_cursor" "line_to" 4 (second tick) (- y-position 3))
1192 (pipeglade-out "chart_cursor" "rel_move_for" 4 "s" (first tick))
1193 (pipeglade-out "chart_cursor" "show_text" 4 (first tick)))
1194 (pipeglade-out "chart_cursor" "stroke" 4)))
1196 (defun axis-ticks (minimum maximum n chart-size reversep)
1197 (let ((range (- maximum minimum)))
1198 (if (zerop range)
1199 (list (list (format nil "~F" minimum) (/ chart-size 2)))
1200 (let* ((a (if reversep
1201 (- (/ chart-size range))
1202 (/ chart-size range)))
1203 (b (if reversep
1204 (* a maximum)
1205 (- (* a maximum) chart-size)))
1206 (min-step (/ range (1+ n)))
1207 (max-step (/ range (1- n)))
1208 (max-exp (log max-step 10))
1209 (int-exp (floor max-exp))
1210 (norm-min (floor (/ min-step (expt 10 int-exp))))
1211 (norm-max (floor (/ max-step (expt 10 int-exp))))
1212 (norm (cond
1213 ((or (= norm-min 1) (= norm-max 1))
1215 ((or (<= norm-min 4 norm-max) (<= norm-min 5 norm-max) (<= norm-min 6 norm-max))
1217 ((or (<= norm-min 2) (<= norm-min 3 norm-max))
1218 2.5)
1219 ((<= 7 norm-max)
1222 norm-max))) ;can't happen
1223 (step (* norm (expt 10 int-exp)))
1224 (start (- minimum (nth-value 1 (fceiling minimum step)))))
1225 (loop
1226 for i from start to maximum by step
1227 collect (list (if (minusp int-exp)
1228 (format nil "~,VF" (- int-exp) i)
1229 (format nil "~A" (round i)))
1230 (- (* a i) b)))))))
1232 (defun draw-accidents (vnk nnk)
1233 (when (string-equal (first *accidents-chart-configuration*) "1")
1234 (let* ((year-min (second *accidents-chart-configuration*))
1235 (year-max (third *accidents-chart-configuration*))
1236 (accidents (accidents-data vnk nnk :year-min year-min :year-max year-max))
1237 (current-station -1)
1238 (zeroth-position -1)
1239 y1-position
1240 y2-position)
1241 (print accidents)
1242 (dolist (accident accidents)
1243 (unless (= current-station (getf accident :nk-station))
1244 (setf y1-position (- *chart-height* zeroth-position))
1245 (setf y2-position zeroth-position)
1246 (setf y0-position (+ (/ *chart-height* 2) zeroth-position)))
1247 (setf current-station (getf accident :nk-station))
1248 (print (list "accident" accident))
1249 (cond ((= 1 (getf accident :fahrtrichtung))
1250 (draw-accident accident (decf y1-position 10))
1251 (print (list "dir 1" accident)))
1252 ((= 2 (getf accident :fahrtrichtung))
1253 (draw-accident accident (incf y2-position 10))
1254 (print (list "dir 2" accident)))
1256 (draw-accident accident (incf y0-position 10))
1257 (print (list "no direction" y0-position current-station))))))))
1259 (defun draw-accident (accident y-position)
1260 "Put graphical representation of accident on chart."
1261 (destructuring-bind (&key nk-station fahrtrichtung unfalltyp unfallkategorie alkohol)
1262 accident
1263 (when (and (numberp alkohol) (plusp alkohol)) (draw-triangle nk-station y-position "lightblue"))
1264 (case unfallkategorie
1265 (1 (draw-rectangle nk-station y-position 10 "black")
1266 (draw-circle nk-station y-position 8 (accident-type-color unfalltyp)))
1267 (2 (draw-circle nk-station y-position 8 (accident-type-color unfalltyp)))
1268 (3 (draw-circle nk-station y-position 6 (accident-type-color unfalltyp)))
1269 (4 (draw-circle nk-station y-position 6 "white")
1270 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1271 (5 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1272 (6 (draw-triangle nk-station y-position "lightblue")
1273 (draw-circle nk-station y-position 4 (accident-type-color unfalltyp)))
1274 (t (draw-circle nk-station y-position 4 (accident-type-color unfalltyp))))))
1276 (defun draw-circle (x y diameter color)
1277 (pipeglade-out "chart_accidents" "set_source_rgba" 2 "black")
1278 (pipeglade-out "chart_accidents" "arc" 2 x y (/ diameter 2) 0 360)
1279 (pipeglade-out "chart_accidents" "stroke_preserve" 2)
1280 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1281 (pipeglade-out "chart_accidents" "fill" 2))
1283 (defun draw-rectangle (x y diameter color)
1284 (let ((radius (/ diameter 2)))
1285 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1286 (pipeglade-out "chart_accidents" "rectangle" 2 (- x radius) (- y radius) diameter diameter)
1287 (pipeglade-out "chart_accidents" "fill" 2)))
1289 (defun draw-triangle (x y color)
1290 (pipeglade-out "chart_accidents" "set_source_rgba" 2 "black")
1291 (pipeglade-out "chart_accidents" "move_to" 2 (- x 3) (- y 6))
1292 (pipeglade-out "chart_accidents" "line_to" 2 (+ x 3) (- y 6))
1293 (pipeglade-out "chart_accidents" "line_to" 2 x (+ y 9))
1294 (pipeglade-out "chart_accidents" "close_path" 2)
1295 (pipeglade-out "chart_accidents" "stroke_preserve" 2)
1296 (pipeglade-out "chart_accidents" "set_source_rgba" 2 color)
1297 (pipeglade-out "chart_accidents" "fill" 2))
1299 (defun accident-type-color (accident-type)
1300 (case accident-type
1301 (1 "green")
1302 (2 "yellow")
1303 (3 "red")
1304 (4 "white")
1305 (5 "lightblue")
1306 (6 "orange")
1307 (7 "black")
1308 (t "darkblue")))
1310 (defun jump-to-station (station &key synchronous)
1311 (when *cruise-control-thread*
1312 (unless synchronous
1313 (return-from jump-to-station)) ;ignore effect of updating station_scale while cruise-controlling
1314 (pipeglade-out "station_scale" "set_value" station))
1315 (save-station station)
1316 (and (bt:threadp *jump-to-station-thread*) (bt:thread-alive-p *jump-to-station-thread*) (bt:destroy-thread *jump-to-station-thread*))
1317 (unless
1318 (ignore-errors
1319 (setf *jump-to-station-thread*
1320 (bt:make-thread
1321 (lambda ()
1322 (let ((table (first *road-section*))
1323 (vnk (second *road-section*))
1324 (nnk (third *road-section*)))
1325 (pipeglade-out "station" "set_text" station)
1326 (place-chart-cursor station)
1327 (if *show-rear-view-p*
1328 (ignore-errors (put-image :vnk vnk :nnk nnk :station station :step 10 :rear-view-p t))
1329 (progn
1330 (pipeglade-out "draw_rearview" "remove" 2)
1331 (pipeglade-out "img_rearview" "set_from_file")))
1332 (if *show-front-view-p*
1333 (ignore-errors (put-image :vnk vnk :nnk nnk :station station :step 10 :rear-view-p nil))
1334 (progn
1335 (pipeglade-out "draw_frontview" "remove" 2)
1336 (pipeglade-out "img_frontview" "set_from_file")))
1337 (put-text-values vnk nnk station)))))
1338 (when synchronous
1339 (bt:join-thread *jump-to-station-thread*)
1340 (and (bt:threadp *rear-view-image-thread*) (bt:join-thread *rear-view-image-thread*))
1341 (and (bt:threadp *front-view-image-thread*) (bt:join-thread *front-view-image-thread*)))
1343 (clear-main-window)))
1345 (defun cruise-control (&key backwardp)
1346 (let ((road-section-length (fourth *road-section*)))
1347 (setf *cruise-control-thread*
1348 (bt:make-thread
1349 (lambda ()
1350 (loop
1352 (jump-to-station (+ (if backwardp (- *big-step*) *big-step*)
1353 (saved-station)) :synchronous t)
1354 (jump-to-station (+ (if backwardp (- *big-step*) *big-step*)
1355 (saved-station)) :synchronous t)
1356 while (<= (+ 0 *big-step*) (saved-station) (- road-section-length *big-step*))))))))
1358 (defun stop-cruise-control ()
1359 (and (bt:threadp *cruise-control-thread*) (bt:thread-alive-p *cruise-control-thread*) (bt:destroy-thread *cruise-control-thread*))
1360 (setf *cruise-control-thread* nil))
1362 (defun put-image (&key vnk nnk station step rear-view-p)
1363 "Put an image along with a labelled station marker on screen."
1364 (with-connection *postgresql-road-network-credentials*
1365 (setf station (or station 0))
1366 (let* ((table (make-symbol (db-credentials-table *postgresql-road-network-credentials*)))
1367 (point-radius 5)
1368 (image-widget (if rear-view-p "img_rearview" "img_frontview"))
1369 (drawing-widget (if rear-view-p "draw_rearview" "draw_frontview"))
1370 (spinner-widget (if rear-view-p "spinner_rearview" "spinner_frontview"))
1371 (time-widget (if rear-view-p "rear_view_time" "front_view_time"))
1372 (global-point-coordinates
1373 (subseq (all-stations table vnk nnk)
1374 (min (length (all-stations table vnk nnk)) station)
1375 (min (length (all-stations table vnk nnk)) (+ station 4))))
1376 (image-data-alist
1377 (get-image-data-alist (road-section-image-data (provenience-string *phoros-url*) table vnk nnk step rear-view-p)
1378 station
1379 step))
1380 (image-arrow-coordinates
1381 (loop
1382 for i across global-point-coordinates
1383 append (image-point-coordinates image-data-alist i)))
1384 (image-label-coordinates (ignore-errors
1385 (list (- (first image-arrow-coordinates) point-radius)
1386 (- (second image-arrow-coordinates) point-radius))))
1387 (image-data (get-image-data (road-section-image-data (provenience-string *phoros-url*) table vnk nnk step rear-view-p) station step)))
1388 (if image-data
1389 (progn
1390 (unless (image-launched-p image-data rear-view-p)
1391 (if rear-view-p
1392 (and (bt:threadp *rear-view-image-thread*) (bt:thread-alive-p *rear-view-image-thread*) (bt:destroy-thread *rear-view-image-thread*))
1393 (and (bt:threadp *front-view-image-thread*) (bt:thread-alive-p *front-view-image-thread*) (bt:destroy-thread *front-view-image-thread*)))
1394 (let ((thread
1395 (bt:make-thread (lambda ()
1396 (with-spinner spinner-widget
1397 (remember-image-being-launched image-data rear-view-p)
1398 (let ((image-filename (ignore-errors
1399 (when image-data (namestring (download-image image-data))))))
1400 (if image-filename
1401 (pipeglade-out image-widget "set_from_file" image-filename)
1402 (pipeglade-out image-widget "set_from_file" "public_html/phoros-logo-plain.png"))))))))
1403 (if rear-view-p
1404 (setf *rear-view-image-thread* thread)
1405 (setf *front-view-image-thread* thread))))
1406 (pipeglade-out time-widget "set_text" (iso-time (image-data-trigger-time image-data)))
1407 (pipeglade-out drawing-widget "remove" 2)
1408 (when image-arrow-coordinates
1409 (pipeglade-out drawing-widget "move_to" 2 (first image-arrow-coordinates) (second image-arrow-coordinates))
1410 (pipeglade-out drawing-widget "line_to" 2 (first (last image-arrow-coordinates 2)) (second (last image-arrow-coordinates 2)))
1411 (pipeglade-out drawing-widget "stroke" 2)
1412 (pipeglade-out drawing-widget "arc" 2 (first image-arrow-coordinates) (second image-arrow-coordinates) point-radius 0 360)
1413 (pipeglade-out drawing-widget "stroke" 2)
1414 (pipeglade-out drawing-widget "move_to" 2 (first image-label-coordinates) (second image-label-coordinates))
1415 (pipeglade-out drawing-widget "rel_move_for" 2 "se" station)
1416 (pipeglade-out drawing-widget "show_text" 2 station)))
1417 (progn
1418 (pipeglade-out image-widget "set_from_file" "public_html/phoros-logo-plain.png")
1419 (pipeglade-out time-widget "set_text")
1420 (pipeglade-out drawing-widget "remove" 2))))))
1422 (defun iso-time (time)
1423 (multiple-value-bind (seconds deciseconds)
1424 (floor time)
1425 (multiple-value-bind (second minute hour date month year day daylight-p zone)
1426 (decode-universal-time seconds)
1427 (format nil "~D-~2,'0D-~2,'0D\\n~2,'0D:~2,'0D:~2,'0D~3,3FZ" year month date hour minute second deciseconds))))
1429 (defun image-point-coordinates (image-data-alist global-point-coordinates)
1430 "Return a list (m n) of image coordinates representing
1431 global-point-coordinates in the image described in image-data-alist
1432 but scaled to fit into *image-size*."
1433 (ignore-errors
1434 (convert-image-coordinates
1435 (photogrammetry :reprojection
1436 image-data-alist
1437 (pairlis '(:x-global :y-global :z-global)
1438 (proj:cs2cs
1439 (list
1440 (proj:degrees-to-radians
1441 (coordinates-longitude global-point-coordinates))
1442 (proj:degrees-to-radians
1443 (coordinates-latitude global-point-coordinates))
1444 (coordinates-ellipsoid-height global-point-coordinates))
1445 :destination-cs (cdr (assoc :cartesian-system image-data-alist)))))
1446 image-data-alist)))
1448 (defun in-image-p (m n)
1449 "Check if m, n lay inside *image-size*."
1450 (and m n (<= 0 m (first *image-size*)) (<= 0 n (second *image-size*))))
1452 (defun-cached sections (table)
1453 "Return list of distinct pairs of vnk, nnk found in table in
1454 current database."
1455 (ignore-errors
1456 (query (:order-by (:select 'vnk 'nnk (:max 'nk-station)
1457 :from (db-credentials-table *postgresql-road-section-credentials*)
1458 :where (:and (:not-null 'vnk) (:not-null 'nnk))
1459 :group-by 'vnk 'nnk)
1460 'vnk 'nnk))))
1462 (defun stations (table vnk nnk &optional (step 1))
1463 "Return a list of plists of :longitude, :latitude,
1464 :ellipsoid-height, :station, :azimuth of stations step metres apart
1465 between vnk and nnk."
1466 (let ((stations
1467 (query
1468 (:order-by
1469 (:select (:as (:st_x 't1.the-geom) 'longitude)
1470 (:as (:st_y 't1.the-geom) 'latitude)
1471 (:as (:st_z 't1.the-geom) 'ellipsoid-height)
1472 (:as 't1.nk-station 'station)
1473 (:as (:st_azimuth 't1.the-geom 't2.the-geom) 'azimuth)
1474 :from (:as table 't1)
1475 :left-join (:as table 't2)
1476 :on (:and (:= 't1.nk-station (:- 't2.nk-station 1))
1477 (:= 't2.vnk vnk)
1478 (:= 't2.nnk nnk))
1479 :where (:and (:= 't1.vnk vnk)
1480 (:= 't1.nnk nnk)
1481 (:= 0 (:% 't1.nk-station step))))
1482 't1.nk-station)
1483 :plists)))
1484 (setf
1485 (getf (nth (- (length stations) 1) stations) :azimuth)
1486 (getf (nth (- (length stations) 2) stations) :azimuth))
1487 stations))
1489 (defun-cached all-stations (table vnk nnk)
1490 "Return a vector of coordinates of all points between vnk and nnk,
1491 station (in metres) being the vector index."
1492 (let* ((stations (stations table vnk nnk))
1493 (result (make-array (list (1+ (getf (first (last stations)) :station)))
1494 :initial-element nil)))
1495 (loop
1496 for i in stations
1497 do (destructuring-bind (&key longitude latitude ellipsoid-height station azimuth)
1499 (setf (svref result station)
1500 (make-coordinates :longitude longitude
1501 :latitude latitude
1502 :ellipsoid-height ellipsoid-height
1503 :azimuth azimuth))))
1504 result))
1506 (defun-cached road-section-image-data (provenience-string table vnk nnk step rear-view-p)
1507 "Return a list of instances of image data corresponding to stations,
1508 which are step metres apart, found in table in current database.
1509 provenience-string only serves as a marker of the provenience of image
1510 data once cached."
1511 (remove nil ;; (mapcar #'(lambda (x)
1512 ;; (apply #'image-data :rear-view-p rear-view-p x))
1513 ;; (stations table vnk nnk step))
1514 (loop
1515 with azimuth-fallback = nil
1516 for station in (stations table vnk nnk step)
1517 when (not (eq (getf station :azimuth) :null))
1518 do (setf azimuth-fallback (getf station :azimuth))
1519 and collect (apply #'image-data :rear-view-p rear-view-p station)
1521 when (and azimuth-fallback
1522 (eq (getf station :azimuth) :null))
1523 do (setf (getf station :azimuth) azimuth-fallback)
1524 and collect (apply #'image-data :rear-view-p rear-view-p station))))
1526 (defun provenience-string (url)
1527 "Turn url recognisably into something suitable as part of a file
1528 name."
1529 (let ((parsed-url (puri:parse-uri url)))
1530 (format nil "~A_~A~{_~A~}"
1531 (puri:uri-host parsed-url)
1532 (puri:uri-port parsed-url)
1533 (cl-utilities:split-sequence
1534 #\/ (puri:uri-path parsed-url) :remove-empty-subseqs t))))
1536 (defun cache-file-name (kind &rest args)
1537 "Return pathname for a cache file distinguishable by kind and args."
1538 (make-pathname :directory *cache-dir*
1539 :name (format nil "~{~:[f~;~:*~(~A~)~]_~}~A"
1540 args
1541 *fasttrack-version*)
1542 :type (string-downcase kind)))
1544 (defun cache-images (road-section-image-data)
1545 "Download images described in road-section-image-data into their
1546 canonical places."
1547 (loop
1548 for i in road-section-image-data
1549 do (download-image i)))
1551 (defun get-image-data (road-section-image-data station step)
1552 "Return image data for the image near station."
1553 (find (* step (round station step)) road-section-image-data
1554 :key #'image-data-station
1555 :test #'=))
1557 (defun get-image-data-alist (road-section-image-data station step)
1558 "Return as an alist data for the image near station."
1559 (image-data-alist (get-image-data road-section-image-data station step)))
1561 (defun image-data (&key longitude latitude ellipsoid-height station azimuth rear-view-p)
1562 "Get from Phoros server image data for location near longitude,
1563 latitude."
1564 (ignore-errors
1565 (let* ((coordinates (make-coordinates :longitude longitude
1566 :latitude latitude
1567 :ellipsoid-height ellipsoid-height
1568 :azimuth azimuth))
1569 (image-data (phoros-nearest-image-data coordinates rear-view-p)))
1570 (when (image-data-p image-data)
1571 (setf (image-data-station image-data) station)
1572 (setf (image-data-station-coordinates image-data) coordinates)
1573 image-data))))
1575 (define-condition phoros-server-error (error)
1576 ((body :reader body :initarg :body)
1577 (status-code :reader status-code :initarg :status-code)
1578 (headers :reader headers :initarg :headers)
1579 (url :reader url :initarg :url)
1580 (reason-phrase :reader reason-phrase :initarg :reason-phrase))
1581 (:report (lambda (condition stream)
1582 (format stream "Can't connect to Phoros server: ~A (~D)"
1583 (reason-phrase condition) (status-code condition)))))
1585 (defun phoros-lib-url (canonical-url suffix)
1586 "Replace last path element of canonical-url by lib/<suffix>."
1587 (let* ((parsed-canonical-url (puri:parse-uri canonical-url))
1588 (old-path (puri:uri-parsed-path parsed-canonical-url))
1589 (new-path (append (butlast old-path) (list "lib" suffix)))
1590 (new-url (puri:copy-uri parsed-canonical-url)))
1591 (setf (puri:uri-parsed-path new-url) new-path)
1592 new-url))
1594 (defun phoros-login (url user-name user-password)
1595 "Log into Phoros server; return T if successful. Try logging out
1596 first."
1597 ;; (setf *phoros-url* url)
1598 (setf drakma:*allow-dotless-cookie-domains-p* t)
1599 (pushnew (cons "application" "json") drakma:*text-content-types* :test #'equal)
1600 (ignore-errors (phoros-logout))
1601 (setf *phoros-cookies* (make-instance 'drakma:cookie-jar))
1602 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1603 (drakma:http-request (puri:parse-uri url) :cookie-jar *phoros-cookies*)
1604 (declare (ignore stream must-close))
1605 (assert (= status-code 200) ()
1606 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1607 (multiple-value-bind (body status-code headers authenticate-url stream must-close reason-phrase)
1608 (drakma:http-request (phoros-lib-url url "authenticate")
1609 :cookie-jar *phoros-cookies*
1610 :form-data t
1611 :method :post
1612 :parameters (pairlis '("user-name" "user-password")
1613 (list user-name user-password)))
1614 (declare (ignore stream must-close))
1615 (assert (< status-code 400) ()
1616 'phoros-server-error :body body :status-code status-code :headers headers :url authenticate-url :reason-phrase reason-phrase)
1617 (let ((body-strings (cl-utilities:split-sequence #\Space (substitute-if-not #\Space #'alphanumericp body))))
1618 (and (not (find "Rejected" body-strings :test #'string=))
1619 (not (find "Retry" body-strings :test #'string=))
1620 (= status-code 200)))))) ;should be 302 (?)
1622 (defun phoros-logout ()
1623 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1624 (drakma:http-request (phoros-lib-url *phoros-url* "logout"))
1625 (declare (ignore stream must-close))
1626 (assert (= status-code 200) ()
1627 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)))
1629 (defun heading (azimuth rear-view-p)
1630 "Return as a string the one of east, west, north, south which best
1631 describes azimuth."
1632 (cond ((<= (* 1/4 pi) azimuth (* 3/4 pi)) (if rear-view-p "west" "east"))
1633 ((<= (* 3/4 pi) azimuth (* 5/4 pi)) (if rear-view-p "north" "south"))
1634 ((<= (* 5/4 pi) azimuth (* 7/4 pi)) (if rear-view-p "east" "west"))
1635 ((or (<= (* 5/4 pi) azimuth pi) (<= 0 (* 1/4 pi))) (if rear-view-p "south" "north"))))
1637 (defun phoros-nearest-image-data (coordinates rear-view-p)
1638 "Return a set of image-data."
1639 (multiple-value-bind (body status-code headers url stream must-close reason-phrase)
1640 (drakma:http-request (phoros-lib-url *phoros-url* "nearest-image-data")
1641 :cookie-jar *phoros-cookies*
1642 :method :post
1643 :content-type "text/plain; charset=UTF-8"
1644 :content (json:encode-json-plist-to-string (list :longitude (coordinates-longitude coordinates)
1645 :latitude (coordinates-latitude coordinates)
1646 :zoom 20
1647 :count 1
1648 :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
1649 (declare (ignore stream must-close))
1650 (assert (= status-code 200) ()
1651 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1652 (unless (string-equal body "null")
1653 (apply #'make-image-data :allow-other-keys t
1654 (plist-from-alist
1655 (car (json:decode-json-from-string body)))))))
1657 (defun download-file (url path)
1658 "Unless already there, store content from url under path. Return
1659 nil if nothing needed storing."
1660 (ensure-directories-exist path)
1661 (with-open-file (file-stream path :direction :output
1662 :element-type 'unsigned-byte
1663 :if-exists nil)
1664 (when file-stream
1665 (multiple-value-bind
1666 (body status-code headers url stream must-close reason-phrase)
1667 (drakma:http-request url
1668 :cookie-jar *phoros-cookies*
1669 :method :get)
1670 (declare (ignore stream must-close))
1671 (setf *t* url)
1672 (assert (= status-code 200) ()
1673 'phoros-server-error :body body :status-code status-code :headers headers :url url :reason-phrase reason-phrase)
1674 (write-sequence body file-stream)
1675 reason-phrase))))
1677 (defun download-image (image-data)
1678 "If not already there, download a png image, shrink it, convert it
1679 into jpg, and store it under the cache path. Return that path."
1680 (multiple-value-bind (url origin-path destination-path)
1681 (image-url image-data)
1682 (unless (probe-file destination-path)
1683 (download-file url origin-path)
1684 (apply #'convert-image-file origin-path destination-path *image-size*)
1685 (delete-file origin-path))
1686 destination-path))
1688 (defun image-launched-p (image-data rear-view-p)
1689 "Check if the image belonging to image-data is the current image."
1690 (multiple-value-bind (url origin-path destination-path)
1691 (image-url image-data)
1692 (let ((remembered-image (if rear-view-p
1693 *rear-view-image-path*
1694 *front-view-image-path*)))
1695 (when (and destination-path remembered-image)
1696 (string= (namestring destination-path) (namestring remembered-image))))))
1698 (defun remember-image-being-launched (image-data rear-view-p)
1699 (multiple-value-bind (url origin-path destination-path)
1700 (image-url image-data)
1701 (if rear-view-p
1702 (setf *rear-view-image-path* destination-path)
1703 (setf *front-view-image-path* destination-path))))
1705 (defun forget-images-being-launched ()
1706 (setf *rear-view-image-path* "")
1707 (setf *front-view-image-path* ""))
1709 (defun image-data-alist (image-data)
1710 "Return an alist representation of image-data."
1711 (when image-data
1712 (loop
1713 for i in (append (mapcar #'ensure-hyphen-before-digit *aggregate-view-columns*) '(station station-coordinates))
1714 collect (intern (string i) 'keyword) into keys
1715 collect (funcall (intern (concatenate 'string (string 'image-data-)
1716 (string i)))
1717 image-data)
1718 into values
1719 finally (return (pairlis keys values)))))
1721 (defun plist-from-alist (alist)
1722 (loop
1723 for (key . value) in alist
1724 collect key
1725 collect value))
1727 (defun image-url (image-data)
1728 "Return an image URL made from ingredients found in image-data, the
1729 corresponding cache path, and the corresponding cache path for the
1730 shrunk image."
1731 (let* ((path
1732 (format nil "~A/~A/~A/~D.png"
1733 (puri:uri-path (phoros-lib-url *phoros-url* "photo"))
1734 (image-data-directory image-data)
1735 (image-data-filename image-data)
1736 (image-data-byte-position image-data)))
1737 (query
1738 (format nil "mounting-angle=~D~
1739 &bayer-pattern=~{~D~#^,~}~
1740 &color-raiser=~{~D~#^,~}"
1741 (image-data-mounting-angle image-data)
1742 (map 'list #'identity (image-data-bayer-pattern image-data))
1743 (map 'list #'identity (image-data-color-raiser image-data))))
1744 (url (puri:copy-uri (puri:parse-uri *phoros-url*) :path path :query query))
1745 (host (puri:uri-host url))
1746 (port (puri:uri-port url))
1747 (cache-directory (append *cache-dir*
1748 (list (format nil "~A_~D" host port))
1749 (cdr (pathname-directory (puri:uri-path url)))))
1750 (cache-name (pathname-name (puri:uri-path url)))
1751 (cache-type (pathname-type (puri:uri-path url))))
1752 (values url
1753 (make-pathname :directory cache-directory
1754 :name cache-name
1755 :type cache-type)
1756 (make-pathname :directory cache-directory
1757 :name cache-name
1758 :type "jpg"))))
1760 (defun convert-image-file (origin-file destination-file width height)
1761 "Convert origin-file into destination-file of a maximum size of
1762 width x height."
1763 (lisp-magick-wand:with-magick-wand (wand :load (namestring origin-file))
1764 (let ((a (/ (lisp-magick-wand:get-image-width wand)
1765 (lisp-magick-wand:get-image-height wand))))
1766 (if (> a (/ width height))
1767 (lisp-magick-wand:scale-image wand width (truncate (/ width a)))
1768 (lisp-magick-wand:scale-image wand (truncate (* a height)) height)))
1769 (lisp-magick-wand:write-image wand (namestring destination-file))))
1771 (defun convert-image-coordinates (original-coordinates-alist image-data-alist)
1772 "Convert image coordinates from original-coordinates-alist for the
1773 image in image-data-alist into a list of coordinates for that image
1774 scaled and centered to *image-size*."
1775 (let* ((original-m (cdr (assoc :m original-coordinates-alist)))
1776 (original-n (cdr (assoc :n original-coordinates-alist)))
1777 (original-width (cdr (assoc :sensor-width-pix image-data-alist)))
1778 (original-height (cdr (assoc :sensor-height-pix image-data-alist)))
1779 (new-width (first *image-size*))
1780 (new-height (second *image-size*))
1781 (scaling-factor (min (/ new-width original-width) (/ new-height original-height)))
1782 (new-m-offset (/ (- new-width (* original-width scaling-factor)) 2))
1783 (new-n-offset (/ (- new-height (* original-height scaling-factor)) 2))
1784 (new-m (+ (* original-m scaling-factor) new-m-offset))
1785 (new-n (- new-height ;flip n
1786 (+ (* original-n scaling-factor) new-n-offset))))
1787 (mapcar #'round (list new-m new-n))))