App/Chart/EmacsMain.pm untested

filter: Statementstmt 0.0% 0 / 371 Branchbran 0.0% 0 / 88 Conditioncond 0.0% 0 / 55 MC/DCmcdc 0.0% 0 / 31 Subroutinesub 0.0% 0 / 60 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 637 CC 45 SCAR 28.5
CC
45
Cov
0%
_do_read
72.0
latest_line
56.0
emacs_command_quote_one
42.0
CRAP 17.2
1 # Copyright 2008, 2009, 2010, 2011, 2014, 2015, 2016, 2017 Kevin Ryde
2  
3 # This file is part of Chart.
4 #
5 # Chart is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3, or (at your option) any later version.
8 #
9 # Chart is distributed in the hope that it will be useful, but WITHOUT ANY
10 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11 # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
12 # details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Chart. If not, see <http://www.gnu.org/licenses/>.
16  
17  
18 # ENHANCE-ME:
19 # remember which latests sent, only give 'update' for them
20  
21  
22 package App::Chart::EmacsMain;
23 use 5.010;
24 use strict;
25 use warnings;
26 use Encode;
27 use Encode::Locale; # for coding system "locale"
28 use IO::Handle;
29 use Lisp::Reader;
30 use Lisp::Printer ('lisp_print');
31 use Lisp::Symbol ('symbol');
32 use POSIX ();
33 use Regexp::Common 'whitespace';
34 use Locale::TextDomain 'App-Chart';
35  
36 use App::Chart;
37  
38 # set this to 1 for development debugging prints
39 use constant { DEBUG => 0,
40 DEBUG_TTY_FILENAME => '/dev/tty7' };
41  
42  
43 use constant PROTOCOL_VERSION => 102;
44 my $emacs_fh;
45  
46 # reopen $fd on $filename with $omode a POSIX::O_WRONLY() etc value
47 # return $fd on success, or undef with $! set on error
48 sub fdreopen {
49 my ($fd, $filename, $omode) = @_;
50 my $file_fd = POSIX::open ($filename, $omode);
51 if (! defined $fd) { return undef; }
52 # print "fdreopen $fd $filename, via $file_fd\n";
53  
54 if (! defined POSIX::dup2 ($file_fd, $fd)) {
55 {
56 local $!;
57 POSIX::close ($file_fd);
58 }
59 return undef;
60 }
61 if (! defined POSIX::close ($file_fd)) { return undef; }
62 return $fd;
63 }
64  
65 sub main {
66 my ($class) = @_;
67  
68 # subprocess unbuffered and utf8
69 binmode (STDIN, ':utf8') or die;
70  
71 # dup-ed to a new descriptor to talk to emacs
72 open $emacs_fh, '>&STDOUT' or die;
73 $emacs_fh->autoflush(1); # emacs_write() does single-string prints
74  
75 # ENHANCE-ME: use one of the IO::Capture or via layer or whatnot to get
76 # perl prints to STDOUT/STDERR and send them up to an emacs buffer, or
77 # message area
78 #
79 # stdout/stderr fds 1 and 2 put to /dev/null to discard other prints
80 my $devnull = File::Spec->devnull;
81 fdreopen (1, $devnull, POSIX::O_WRONLY())
82 // die "Cannot send STDOUT to $devnull: ", Glib::strerror($!);
83 POSIX::dup2 (1, 2) // die;
84  
85 if (DEBUG) {
86 # fds 1 and 2 changed (again) to DEBUG_TTY_FILENAME, if it's possible to
87 # open that
88 if (fdreopen (1, DEBUG_TTY_FILENAME, POSIX::O_WRONLY())) {
89 POSIX::dup2 (1, 2) // die "Cannot dup fd 1 to fd 2: $!";
90  
91 print "EmacsMain started, emacs_fh fd=",fileno($emacs_fh),
92 ", diagnostics on ",DEBUG_TTY_FILENAME,"\n";
93 print " STDOUT fd ",fileno(STDOUT),", STDERR fd ",fileno(STDERR),"\n";
94 STDOUT->autoflush(1);
95 STDERR->autoflush(1); # probably true already
96 }
97 }
98  
99  
100 # initial message
101 emacs_write (symbol('init'), 'UTF-8', PROTOCOL_VERSION);
102  
103 my $mainloop = Glib::MainLoop->new;
104 STDIN->blocking(0);
105 Glib::IO->add_watch (fileno(STDIN), ['in', 'hup', 'err'], \&_do_read,
106 $mainloop);
107  
108 $Lisp::Reader::SYMBOLS_AS_STRINGS = 1;
109  
110 my $dirb = App::Chart::chart_dirbroadcast();
111 $dirb->listen;
112 $dirb->connect ('delete-symbol', \&completions_update);
113 $dirb->connect ('symlist-content-changed', \&_do_symlist_content_changed);
114 $dirb->connect ('symlist-content-inserted', \&_do_symlist_content_inserted);
115 $dirb->connect ('symlist-content-deleted', \&_do_symlist_content_deleted);
116 $dirb->connect ('symlist-content-reordered',\&_do_symlist_content_reordered);
117 $dirb->connect ('symlist-list-changed', \&_do_symlist_list_changed);
118  
119 $dirb->connect ('latest-changed', \&send_update);
120 $dirb->connect ('data-changed', \&send_update);
121  
122 Glib->install_exception_handler (\&exception_handler);
123 ## no critic (RequireLocalizedPunctuationVars)
124 $SIG{'__WARN__'} = \&exception_handler;
125 $mainloop->run;
126 }
127  
128 # 'data-changed' and 'latest-changed'
129 sub send_update {
130 my ($changed) = @_;
131 if (DEBUG) { print "Changed: ",join(' ',keys %$changed),"\n"; }
132 emacs_write (symbol('update'), [ keys %$changed ]);
133  
134 # this is a bit excessive, only really want to know if new symbols have
135 # been added to the latest quotes
136 completions_update();
137 }
138  
139 sub exception_handler {
140 my ($msg) = @_;
141 # perhaps some modules like LWP will put through a locale $! or similar
142 unless (utf8::is_utf8($msg)) { $msg = Encode::decode('locale',$msg); }
143 if (DEBUG) { print "Error ", $msg; }
144  
145 $msg =~ s/$RE{ws}{crop}//g; # leading and trailing whitespace
146  
147 # $trace->as_string has non-ascii de-fanged to something printable, so it
148 # can go straight out
149 #
150 my $backtrace;
151 if (eval { require Devel::StackTrace; }) {
152 $backtrace = Devel::StackTrace->new->as_string;
153 $msg .= __('See *chart-process-backtrace* buffer');
154 }
155 emacs_write (symbol('error'), $msg, $backtrace);
156  
157 return 1; # stay installed
158 }
159  
160 sub emacs_write {
161 if (DEBUG >= 2) { require Data::Dumper;
162 print Data::Dumper::Dumper(\@_); }
163 if (DEBUG) { print "To emacs: ",lisp_print([@_]),"\n"; }
164 print $emacs_fh lisp_print([@_]),"\n";
165 }
166  
167 my $buf = '';
168  
169 sub _do_read {
170 my ($fd, $conditions, $mainloop) = @_;
171  
172 for (;;) {
173 if (DEBUG >= 2) { print " read more at ",length($buf),"\n"; }
174 my $got = read STDIN, $buf, 8192, length($buf);
175 if (DEBUG >= 2) { print " got ",$got//'undef'," $!\n"; }
176 if (! defined $got) {
177 if ($! == POSIX::EWOULDBLOCK()) { last; } # no more data for now
178 if ($!) {
179 print STDERR "Read error: ",Glib::strerror($!),"\n";
180 }
181 $mainloop->quit;
182 return 0;
183 }
184 if ($got == 0) {
185 ## no critic (ProhibitExit, ProhibitExitInSubroutines)
186 exit 0;
187 }
188 }
189  
190 my ($aref, $endpos) = Lisp::Reader::lisp_read ($buf);
191 $buf = substr ($buf, $endpos);
192  
193 if (DEBUG) { require Data::Dumper;
194 print "Receive: ",Data::Dumper::Dumper($aref);
195 print "leaving buf ",length($buf),"\n"; }
196 foreach my $list (@$aref) {
197 call_command ($list);
198 }
199 return 1; # stay connected
200 }
201  
202 sub call_command {
203 my ($list) = @_;
204 my $lisp_command = shift @$list;
205 my $command = $lisp_command;
206 $command =~ tr/-/_/;
207 $command = "emacs_command_$command";
208 if (DEBUG) { print "Call $command\n"; }
209 if (defined &$command) {
210 no strict;
211 &$command (@$list);
212 } else {
213 emacs_write (symbol('error'), "Unknown $command ($lisp_command)", undef);
214 }
215 }
216  
217 #-----------------------------------------------------------------------------
218 # broadcast handlers
219  
220 # 'symlist-list-changed' handler
221 sub _do_symlist_list_changed {
222 my ($key, $pos) = @_;
223 if ($key eq 'all' || $key eq 'favourites') {
224 completions_update();
225 }
226 emacs_write (symbol('symlist-list-changed'), [ $key ]);
227 }
228 # 'symlist-content-changed' handler
229 sub _do_symlist_content_changed {
230 my ($key, $pos) = @_;
231 if ($key eq 'all' || $key eq 'favourites') {
232 completions_update();
233 }
234 emacs_write (symbol('symlist-update'), [ $key ]);
235 }
236 # 'symlist-content-deleted' handler
237 sub _do_symlist_content_deleted {
238 my ($key, $pos) = @_;
239 if ($key eq 'all' || $key eq 'favourites') {
240 completions_update();
241 }
242 emacs_write (symbol('symlist-update'), [ $key ]);
243 }
244 # 'symlist-content-inserted' handler
245 sub _do_symlist_content_inserted {
246 my ($key, $pos) = @_;
247 if ($key eq 'all' || $key eq 'favourites') {
248 completions_update();
249 }
250 emacs_write (symbol('symlist-update'), [ $key ]);
251 }
252 # 'symlist-content-reordered' handler
253 sub _do_symlist_content_reordered {
254 my ($key, $pos) = @_;
255 if ($key eq 'all' || $key eq 'favourites') {
256 completions_update();
257 }
258 emacs_write (symbol('symlist-update'), [ $key ]);
259 }
260  
261  
262  
263 #-----------------------------------------------------------------------------
264  
265 # return string for $latest
266 sub latest_line {
267 my ($latest) = @_;
268 my $excess = 0;
269 my $ret = '';
270 my $add = sub {
271 my ($width, $str) = @_;
272 my $this = sprintf ('%*s', $width, $str//'');
273 $excess += length($this) - abs($width);
274 while ($excess > 0 && $ret =~ / $/) {
275 $ret = substr ($ret, 0, -1);
276 $excess--;
277 }
278 while ($excess > 0 && length($this) > 1 && $this =~ /^ /) {
279 $this = substr ($this, 1);
280 $excess--;
281 }
282 $ret .= $this;
283 };
284 $add->(-9, $latest->{'symbol'});
285 my $bid = $latest->{'bid'};
286 my $offer = $latest->{'offer'};
287 $add->(7, format_price($bid));
288 my $slash = (defined $bid && defined $offer && $bid > $offer ? 'x' : '/');
289 $add->(1, $slash);
290 $add->(-7, format_price($offer));
291 $add->(1, ' ');
292 $add->(7, format_price($latest->{'last'}));
293 $add->(1, ' ');
294 $add->(6, format_price($latest->{'change'}));
295 $add->(1, ' ');
296 $add->(7, format_price($latest->{'low'}));
297 $add->(1, ' ');
298 $add->(7, format_price($latest->{'high'}));
299 $add->(1, ' ');
300 $add->(7, $latest->formatted_volume);
301 $add->(1, ' ');
302 $add->(7, $latest->short_datetime);
303 $add->(1, ' ');
304  
305 my @notes;
306 if ($latest->{'halt'}) { push @notes, __('halt'); }
307 if ($latest->{'limit_up'}) { push @notes, __('limit up'); }
308 if ($latest->{'limit_down'}) { push @notes, __('limit down'); }
309 if (my $note = $latest->{'note'}) { push @notes, $note; }
310 if (my $error = $latest->{'error'}) { push @notes, $error; }
311 my $note = join (', ', @notes);
312 $add->(length($note), $note);
313  
314 return $ret;
315 }
316  
317 sub format_price {
318 my ($str) = @_;
319 if (! defined $str) { return ''; }
320 my $nf = App::Chart::number_formatter();
321 return eval { $nf->format_number ($str, App::Chart::count_decimals($str), 1) }
322 // __('[bad]');
323 }
324  
325 sub latest_to_face {
326 my ($latest) = @_;
327 if ($App::Chart::Gtk2::Job::Latest::inprogress{$latest->{'symbol'}}) {
328 return symbol('chartprog-in-progress');
329 }
330 my $change = $latest->{'change'} || 0;
331 if ($change > 0) {
332 return symbol('chartprog-up');
333 } elsif ($change < 0) {
334 return symbol('chartprog-down');
335 }
336 return undef;
337 }
338  
339 # return element list [$symbol, $string, $face, $help]
340 sub latest_elem {
341 my ($symbol) = @_;
342 require App::Chart::Latest;
343 my $latest = App::Chart::Latest->get ($symbol);
344  
345 my $face = latest_to_face($latest);
346  
347 my $help = join (' - ', $symbol, $latest->{'name'}//'') . "\n";
348 if (my $quote_date = $latest->{'quote_date'}) {
349 my $quote_time = $latest->{'quote_time'} || '';
350 $help .= __x("Quote: {quote_date} {quote_time}",
351 quote_date => $quote_date,
352 quote_time => $quote_time)
353 . "\n";
354 }
355 if (my $last_date = $latest->{'last_date'}) {
356 my $last_time = $latest->{'last_time'} || '';
357 $help .= __x("Last: {last_date} {last_time}",
358 last_date => $last_date,
359 last_time => $last_time);
360 $help .= "\n";
361 }
362 $help .= __x("{location} time; source {source}",
363 location => App::Chart::TZ->for_symbol($symbol)->name,
364 source => $latest->{'source'});
365  
366 return [$symbol, latest_line($latest), $face, $help];
367 }
368  
369 #-----------------------------------------------------------------------------
370 # commands
371  
372 # send latest lines for SYMBOL-LIST
373 sub emacs_command_latest_get_list {
374 my ($symbol_list) = @_;
375  
376 # write in chunks of 20 symbols
377 while (@$symbol_list) {
378 my @part = splice @$symbol_list, 0, 20;
379 emacs_write (symbol('latest-line-list'),
380 [ map { latest_elem($_) } @part ]);
381 }
382 }
383  
384 sub emacs_command_request_symbols {
385 my ($symbol_list) = @_;
386 require App::Chart::Gtk2::Job::Latest;
387 App::Chart::Gtk2::Job::Latest->start ($symbol_list);
388 }
389  
390 sub emacs_command_request_explicit {
391 goto &emacs_command_request_symbols;
392 }
393  
394 # send the symbols in symlist $key
395 sub emacs_command_get_symlist {
396 my ($key) = @_;
397 require App::Chart::Gtk2::Symlist;
398 my $symlist = App::Chart::Gtk2::Symlist->new_from_key ($key);
399 emacs_write (symbol('symlist-list'), symbol($key), $symlist->symbol_listref);
400 }
401  
402 sub emacs_command_synchronize {
403 my ($n) = @_;
404 emacs_write (symbol('synchronize', $n));
405 }
406  
407 sub emacs_command_synchronous {
408 my ($seq, $func, @args) = @_;
409 if (DEBUG) { print " synchronous to $func\n"; }
410 emacs_write (symbol('synchronous'), $seq,
411 call_command ([$func, @args]));
412 }
413  
414 sub emacs_command_noop {
415 }
416  
417  
418 #-----------------------------------------------------------------------------
419 # symlist manipulations
420  
421 # (request-symlist KEY)
422 # Begin a download of latest prices for all symbols in symlist KEY.
423 #
424 sub emacs_command_request_symlist {
425 my ($key) = @_;
426 require App::Chart::Gtk2::Symlist;
427 my $symlist = App::Chart::Gtk2::Symlist->new_from_key ($key);
428 require App::Chart::Gtk2::Job::Latest;
429 App::Chart::Gtk2::Job::Latest->start_symlist ($symlist);
430 }
431  
432 sub emacs_command_request_explicit_symlist {
433 goto &emacs_command_request_symlist;
434 }
435  
436 # (symlist-delete KEY POS COUNT)
437 #
438 sub emacs_command_symlist_delete {
439 my ($key, $pos, $count) = @_;
440 my $symlist = App::Chart::Gtk2::Symlist->new_from_key ($key);
441 foreach (1 .. $count) {
442 my $iter = $symlist->iter_nth_child (undef, $pos);
443 $symlist->remove ($iter);
444 }
445 }
446  
447 sub emacs_command_symlist_insert {
448 my ($key, $pos, $symbol_list) = @_;
449 my $symlist = App::Chart::Gtk2::Symlist->new_from_key ($key);
450 foreach my $symbol (@$symbol_list) {
451 $symlist->insert_symbol_at_pos ($symbol, $pos++);
452 }
453 }
454  
455  
456 #-----------------------------------------------------------------------------
457 # completion - symbols
458  
459 sub emacs_command_get_completion_symbols {
460 my %symbols;
461  
462 # # favourites list symbols
463 # {
464 # require App::Chart::Gtk2::Symlist::Favourites;
465 # if (my $favourites = App::Chart::Gtk2::Symlist::Favourites->instance) {
466 # my $href = $favourites->hash;
467 # %symbols = %$href; # copy
468 # }
469 # }
470  
471 # all database data symbols
472 require App::Chart::Database;
473 @symbols{App::Chart::Database->symbols_list()} = (); # hash slice
474  
475 require App::Chart::DBI;
476 my $dbh = App::Chart::DBI->instance;
477 foreach my $statement (# all latest record symbols
478 'SELECT symbol FROM latest',
479 # all symbols in all lists
480 'SELECT symbol FROM symlist_content') {
481 my $sth = $dbh->prepare_cached($statement);
482 my $a = $dbh->selectcol_arrayref ($sth);
483 @symbols{@$a} = (); # hash slice
484 }
485 return [ map {[$_]} sort keys %symbols ];
486 }
487  
488 sub completions_update {
489 emacs_write (symbol('completion-symbols-update'));
490 }
491  
492  
493 #-----------------------------------------------------------------------------
494 # symlist alist
495  
496 # the `chart-symlist-alist' data, being a list of elements (NAME KEY
497 # EDITABLE), is sent up as an asynch, and with a dummy return value
498 #
499 # this suits chart-watchlist startup which doesn't want to wait, and
500 # chart-symlist-alist forced initialization, which does want to wait
501 #
502 sub emacs_command_get_symlist_alist {
503 # my $model = App::Chart::Gtk2::SymlistListModel->instance;
504 # my @list;
505 # $model->foreach (sub {
506 # my ($model, $path, $iter) = @_;
507 # $model->get_value ($iter, $model->COL_NAME))
508 # $model->get_value ($iter, $model->COL_KEY))
509 # column_contents$model
510  
511 require App::Chart::Gtk2::Symlist;
512 emacs_write (symbol('symlist-alist'),
513 [ map { my $symlist = $_;
514 [ $symlist->name,
515 symbol($symlist->key),
516 $symlist->can_edit ? symbol('t') : undef ]
517 }
518 App::Chart::Gtk2::Symlist->all_lists ]);
519 return undef;
520 }
521  
522  
523 #-----------------------------------------------------------------------------
524 # individual `chart-quote'
525  
526 # Return [$symbol, $string, $face, $help] intended for display in the
527 # message area of an `M-x chart-quote' single-symbol quote.
528 #
529 # The return is the current latest quote. Nothing is downloaded. (That's
530 # done by a separate `request-explicit'.)
531 #
532 # The symbol name and timezone are appended to the $string returned so as to
533 # show that as a second line in the message area (in GNU emacs which has
534 # multi-line messages, but not XEmacs circa its 21.4).
535 #
536 sub emacs_command_quote_one {
537 my ($symbol) = @_;
538 if (DEBUG) { print " quote-one $symbol\n"; }
539  
540 my $elem = latest_elem ($symbol);
541 my $extra = '';
542 if (length($symbol) > 9) {
543 $extra = $symbol;
544 }
545  
546 # " - name", when the name is available
547 my $latest = App::Chart::Latest->get ($symbol);
548 if (my $name = $latest->{'name'}) {
549 if ($extra) {
550 $extra = join (' - ', $extra, $name);
551 } else {
552 $extra = $name;
553 }
554 }
555 my $timezone = App::Chart::TZ->for_symbol($symbol);
556 if ($timezone != App::Chart::TZ->loco) {
557 $extra = join (' ', $extra, '[' . $timezone->name . ']');
558 }
559 $elem->[1] = join ("\n", $elem->[1], $extra);
560  
561 return $elem;
562 }
563  
564 #-----------------------------------------------------------------------------
565 # latest records
566  
567 sub emacs_command_get_latest_record {
568 my ($symbol) = @_;
569 require App::Chart::Latest;
570 my $latest = App::Chart::Latest->get ($symbol);
571  
572 return [ symbol('symbol'), $latest->{'symbol'},
573 symbol('name'), $latest->{'name'},
574 symbol('quote-date'), $latest->{'quote_date'},
575 symbol('quote-time'), $latest->{'quote_time'},
576 symbol('bid'), $latest->{'bid'},
577 symbol('offer'), $latest->{'offer'},
578 symbol('open'), $latest->{'open'},
579 symbol('high'), $latest->{'high'},
580 symbol('low'), $latest->{'low'},
581 symbol('last'), $latest->{'last'},
582 symbol('last-date'), $latest->{'last_date'},
583 symbol('last-time'), $latest->{'last_time'},
584 symbol('change'), $latest->{'change'},
585 symbol('volume'), $latest->{'volume'},
586 symbol('decimals'), 0,
587 symbol('note'), $latest->{'note'},
588 symbol('source'), $latest->{'source'},
589 symbol('face'), latest_to_face($latest),
590 ];
591 }
592  
593  
594 #-----------------------------------------------------------------------------
595 # spreadsheet support
596  
597 # return when SYMBOL-LIST has been downloaded
598 # (define-public (emacs-command-request-symbols-synchronous symbol-list)
599 # (call-with-current-continuation
600 # (lambda (cont)
601 # (define (callback this-symbol-list)
602 # (set! this-symbol-list (remove latest-in-progress? this-symbol-list))
603 # (set! symbol-list (lset-difference string=?
604 # symbol-list this-symbol-list))
605 # (if (null? symbol-list)
606 # (begin
607 # (notify-disconnect 'latest-update callback)
608 # (cont #f))))
609 # (notify-connect 'latest-update callback)
610 # (c-main-enq! latest-request-symbols symbol-list)
611 # (c-main-goto-top)))
612 # 'nil)
613  
614 1;
615 __END__