summaryrefslogtreecommitdiff
path: root/src/dynmenu.cpp
blob: d2316391ca19f45fba376bf828f8accacc7a462b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
#include <unistd.h>
#include <curses.h>
#include <string.h>
#include <string>
#include <vector>
#include <assert.h>
#include <algorithm>
#include <signal.h>

class DynmenuView;
typedef DynmenuView *DynmenuViewRef; // boost::shared_ptr<DynmenuView>

class Dynmenu
{
  std::string m_title;
  std::string m_welcomeText;
  std::vector<DynmenuViewRef> views;

  class Item {
    char *desc;
    Item(const Item &i) { assert(false); }
  public:
    std::string id;
    std::string key;
    std::string cmd;
    const char *getText() const { return desc; }
    void setText(const char *desc) { 
      if(this->desc) delete [] this->desc;
      this->desc=new char[strlen(desc)+1];
      strcpy(this->desc,desc); 
    }
    Item(const char *id, const char *key, const char *desc, const char *cmd) :
      id(id), key(key), cmd(cmd) { this->desc=NULL; setText(desc); }
    ~Item() { delete [] desc; }
  };

  std::vector<Item *> items;

  typedef std::vector<Item *>::iterator ItemIterator;
  struct has_id  : public std::binary_function<Item*,const char *,bool> {
    bool operator ()( Item *item , const char *id) const  { return item->id==id; }
  };

  int m_selection;

public:

  enum notify_id { TITLE, WELCOMETEXT, SELECTION };
  void redraw() { sendNotify(TITLE); sendNotify(WELCOMETEXT); sendNotify(SELECTION); }
  void setTitle(const char *s) { m_title = s; sendNotify(TITLE); }
  const char*title() const { return m_title.c_str(); }
  void setWelcomeText(const char *s) { m_welcomeText = s; sendNotify(WELCOMETEXT); }
  const char *welcomeText() const { return m_welcomeText.c_str(); }
  void setItem(const char *id, const char *sortkey, const char *desc, const char *cmd);
  void delItem(const char *id);
  int selection() const { return m_selection; }
  bool haveSelection() const { return m_selection >= 0; }
  void selectItem(const char *id);
  const char *selectedCommand() const { return haveSelection() ? items[m_selection]->cmd.c_str() : ""; }
  void cursorUp()   { if( m_selection>0) m_selection--; sendNotify(SELECTION); }
  void cursorDown() { if( m_selection+1<items.size()) m_selection++; sendNotify(SELECTION); }
  Dynmenu() { m_selection = -1; }
  ~Dynmenu() { for(int i=0;i<items.size();i++) delete items[i]; }

  void registerView(DynmenuViewRef view);
private:
  void sendNotify(notify_id id);
  void sendItemInsertion(int idx, const char *text);
  void sendItemChanged(int idx, const char *text);
  ItemIterator findItem(const char *id);
};

class DynmenuView
{
public:
  virtual void notify(Dynmenu *menu, Dynmenu::notify_id id) = 0;
  virtual void itemInserted(Dynmenu *menu, int index, const char *text ) = 0;
  virtual void itemChanged(Dynmenu *menu, int index, const char *text ) = 0;
  virtual ~DynmenuView() {}
};

class DynmenuSimpleView : public DynmenuView
{
public:
  virtual void notify(Dynmenu *menu, Dynmenu::notify_id id) { 
    printf("notify %p %i\n", menu, id );
  }
  virtual void itemInserted(Dynmenu *menu, int index, const char *text ) {
    //printf("itemInserted %p %i \"%s\" \"%s\"\n", menu, index, text, menu->items[index]->cmd.c_str() );
    printf("itemInserted %p %i \"%s\"\n", menu, index, text );
  }
  virtual void itemChanged(Dynmenu *menu, int index, const char *text ) {
    printf("itemChanged %p %i \"%s\"\n", menu, index, text );
  }
  virtual ~DynmenuSimpleView() {}
};


Dynmenu::ItemIterator Dynmenu::findItem(const char *id)
{
  using namespace std;
  ItemIterator ret = find_if( items.begin(), items.end(), bind2nd( has_id(), id )  );
  return ret;
}

void Dynmenu::setItem(const char *id, const char *sortkey, const char *desc, const char *cmd)
{
  std::vector<Item*>::iterator i;
  i = findItem(id);
  if(i==items.end()) {
    items.push_back( new Item(id,sortkey,desc,cmd) );
    // TODO: sort
    sendItemInsertion( items.size()-1, items.back()->getText() );
    if(m_selection==-1) {
        m_selection=items.size()-1;
        sendNotify(SELECTION);
    }
  }
  else {
    (*i)->cmd = cmd;
    (*i)->setText(desc);
    (*i)->key = sortkey; // TODO: resort
    sendItemChanged( i - items.begin(), (*i)->getText() );
  }
}

void Dynmenu::selectItem(const char *id)
{
  std::vector<Item*>::iterator i;
  i = findItem(id);
  if(i!=items.end()) {
    m_selection = i - items.begin();
    sendNotify(SELECTION);
  }
}

void Dynmenu::delItem(const char *id){}

void Dynmenu::registerView(DynmenuViewRef view)
{
  view->notify(this,TITLE);
  view->notify(this,WELCOMETEXT);
  std::vector<Item*>::iterator i;
  for(i=items.begin(); i!=items.end(); i++ ) {
    view->itemInserted( this, i - items.begin(), (*i)->getText() );
  }
  view->notify(this,SELECTION);
  views.push_back(view);
}

void Dynmenu::sendNotify(notify_id id)
{
  for( std::vector<DynmenuViewRef>::iterator i=views.begin(); i!=views.end(); i++ ) {
    (*i)->notify(this, id);
  }
}
void Dynmenu::sendItemInsertion(int idx, const char *text )
{
  for( std::vector<DynmenuViewRef>::iterator i=views.begin(); i!=views.end(); i++ ) {
    (*i)->itemInserted(this, idx, text);
  }
}
void Dynmenu::sendItemChanged(int idx, const char *text )
{
  for( std::vector<DynmenuViewRef>::iterator i=views.begin(); i!=views.end(); i++ ) {
    (*i)->itemChanged(this, idx, text);
  }
}

int _g_y = 0;

#define kdprintf(fmt,...) \
  { char buf[200]; _g_y++; sprintf( buf, fmt "\n", ## __VA_ARGS__);  mvaddnstr(_g_y,1,buf,strlen(buf)); refresh(); }
#define dprintf(fmt,...) 


struct TextBox
{
  int y,x,w,h;
  TextBox() : y(0),x(0),w(0),h(0) {}
  void update(int x_, int y_, int w_, int h_) { y=y_;x=x_;w=w_;h=h_; }
};


class LineDrawer
{
public:
  virtual void drawLine(WINDOW *win, int width, int number) = 0;
  virtual int size() const = 0;
};

class ScrollWindow
{
  WINDOW *win;
  int top_index;
  LineDrawer *drawer;
  void getExtants(int &maxy, int &maxx, int &count);
public:
  void redraw();
  ScrollWindow() : win(NULL), top_index(0), drawer(NULL) {}
  void setWin(WINDOW *w) { win=w; redraw(); }
  void setLineDrawer(LineDrawer *d) { drawer = d; redraw(); }
  void doScroll(int delta);
  void scrollTo(int start, int end);
  void invalidate(int start, int end);
  void changedSize();
};

void ScrollWindow::getExtants(int &maxy, int &maxx, int &count)
{
  getmaxyx(win,maxy,maxx);
  count = drawer->size();
}

void ScrollWindow::redraw()
{
  if(!win || !drawer) return;
  int maxy,maxx,count;
  getExtants(maxy,maxx,count);
  wborder(win, 0, 0, top_index>0 ? '.' : 0, count < top_index+maxy-1 ? 0 : '.' , 0, 0, 0, 0);
  for(int y=1,i=top_index;y<maxy-1;y++) {
    if( i<count ) {
      wmove(win,y,1);
      drawer->drawLine(win,maxx-2,i++);
    }
  }
  wrefresh(win);
}

void ScrollWindow::invalidate(int start, int end)
{
  int maxy,maxx,count;
  if( end <= top_index ) return;
  getExtants(maxy,maxx,count);
  if( start > top_index+maxy-2 ) return;

  if(start < top_index ) start = top_index;
  if(end > top_index+maxy-2 ) end = top_index+maxy-2;
  //if(end > count ) end = count;  


  int starty = 1 + start - top_index;
  int stopy = starty + end - start;

  for(int y=starty,i=start;y<stopy;y++) {
    //if( i<count ) {
      wmove(win,y,1);
      drawer->drawLine(win,maxx-2,i++);
    //}
  }
  wrefresh(win);
}

void ScrollWindow::scrollTo(int start, int end)
{
  if( start < top_index ) doScroll(start-top_index);
  int maxy,maxx,count;
  getExtants(maxy,maxx,count);
  if( end > top_index+maxy-2 && start>top_index) {
    int delta=end-top_index-maxy+2;
    if( top_index+delta > start ) delta = start - top_index;
    doScroll(delta);
  }
}

void ScrollWindow::changedSize()
{
  int maxy,maxx,count;
  getExtants(maxy,maxx,count);
  wmove(win,maxy-1,1);
  if( top_index+maxy-2<count) {
    whline(win,'.',maxx-2);
    wrefresh(win);
  }
  else if( top_index+maxy-2==count) {
    whline(win,0,maxx-2);
    wrefresh(win);
  }
}

void ScrollWindow::doScroll(int delta)
{
  if(!win || !drawer) return;
  //assert(delta>=-1 && delta<=1);
  int maxy,maxx,count;
  getExtants(maxy,maxx,count);

  if( top_index+delta<0 ) delta = -top_index;
  if (delta>0 && top_index>0 && top_index+maxy-1+delta>count) delta=count-top_index-maxy+2;
  if (top_index+delta>count)  delta=0;

  if(delta==0) return;
  dprintf("scrolling win=%p, drawer=%p, top_index+delta=%i, v=%i, count=%i", win, drawer, top_index+delta, top_index+maxy-1+delta, count);

  dprintf("scrolling %i", delta);

  WINDOW *w = derwin(win, maxy-2,maxx-2,1,1);
  scrollok(w,true);
  wscrl(w,delta);
  scrollok(w,false);
  touchwin(win);

  if( top_index==0 ) {
    wmove(win,0,1);
    whline(win,'.',maxx-2);
  }
  if( top_index+maxy-2==count) {
    wmove(win,maxy-1,1);
    whline(win,'.',maxx-2);
  }
  top_index += delta;
  int y = delta<0 ? 0 : maxy-2-delta;
  int i = y + top_index;
  dprintf("scroll values i=%i, y=%i", i, y);
  delta = delta<0 ? -delta : delta;
  for(int j=0;j<delta;j++) {
    wmove(w,y++,0);
    if(i<count) drawer->drawLine(w,maxx-2,i++);
    
  }
  wrefresh(w);
  delwin(w);
  if( top_index==0 ) {
    wmove(win,0,1);
    whline(win,0,maxx-2);
  }
  if( top_index+maxy-2==count) {
    wmove(win,maxy-1,1);
    whline(win,0,maxx-2);
  }
  wrefresh(win);
}

/*
class ItemDrawer : public LineDrawer
{
public:
  void drawLine(WINDOW *win, int width, int number);
  int size() const { return 50; }
};

void ItemDrawer::drawLine(WINDOW *win, int width, int number)
{
  char buf[200];
  sprintf(buf, "This is line #%i.", number );
  waddnstr(win,buf, width);
}
*/

class DynmenuCursesView : public DynmenuView, public LineDrawer
{
  int maxx, maxy;
  WINDOW *win;
  TextBox titleBox;
  TextBox welcomeBox;
  WINDOW *itemwin;
  ScrollWindow itemScroll;
  struct Item {
    int top;
    std::vector<const char *> text;
    int compare(int line) { 
      if(line<top) return -1;
      else if(line>=top+text.size()) return 1;
      else return 0; 
    }
  };
  std::vector<Item> items;
  int cached_index;
  int selected;
public:
  DynmenuCursesView() : win(NULL),itemwin(NULL), maxx(0), maxy(0), cached_index(0), selected(-1) {  
    itemScroll.setLineDrawer(this);
  }
  ~DynmenuCursesView() { delwin(itemwin); }
  void show(WINDOW *win);
  void notify(Dynmenu *menu, Dynmenu::notify_id id);
  void itemInserted(Dynmenu *menu, int index, const char *text );
  void itemChanged(Dynmenu *menu, int index, const char *text );

  // LineDrawer interface
  void drawLine(WINDOW *win, int width, int number);
  int size() const { if(items.size()==0) return 0; else return items.back().top + items.back().text.size(); }
};

void DynmenuCursesView::drawLine(WINDOW *win, int width, int number )
{
  int i = cached_index;
  while( items[i].compare(number)>0 && i<items.size()-1 ) i++;
  while( items[i].compare(number)<0 && i>0 ) i--;
  if( items[i].compare(number)!=0 ) {
    // If out of range, clear row
    wattroff(win, A_STANDOUT);
    for(int i=0;i<width;i++) waddch(win,' ');
    return;
  }
  cached_index = i;
  Item &item = items[cached_index];
  i = number - item.top;
  const char *end = NULL;
  if( i < item.text.size()-1 ) end = item.text[i+1]-1;
  if(!end) for(end=item.text[i];*end;end++);
  size_t len = end - item.text[i];
  len = len>width ? width : len;
  // TODO: draw selection
  if( selected == cached_index ) 
    wattron(win, A_STANDOUT);
  else 
    wattroff(win, A_STANDOUT);
  waddnstr( win, item.text[i], len );
  int mright = width - len;
        for(int j=0;j<mright;j++) waddstr(win," ");
  wattroff(win, A_STANDOUT);
}

void DynmenuCursesView::itemInserted(Dynmenu *menu, int index, const char *text)
{
  std::vector<Item>::iterator item = items.insert( items.begin() + index, Item() );
  const char *p = text;
  item->text.push_back(p);
  for(;;) {
    while( *p && *p!='\n' ) p++;
    if(*p) p++;
    if(*p) item->text.push_back(p);
    else break;
  }
  int firstrow = 0;
  if(item!=items.begin())  {
    item->top = (item-1)->top + (item-1)->text.size();
  }
  else 
    item->top = 0;

  firstrow = item->top;
  if((item+1)!=items.end()) {
    size_t newrows = item->text.size();
    for( item++; item!=items.end(); item++ ) item->top += newrows;
  }
  itemScroll.invalidate( firstrow, size() );
  itemScroll.changedSize();
  wrefresh(win);
}

void DynmenuCursesView::itemChanged(Dynmenu *menu, int index, const char *text)
{
  std::vector<Item>::iterator item = items.begin() + index;
  size_t oldsize = item->text.size();
  int lastrow = items.back().top + items.back().text.size();
  item->text.clear();
  const char *p = text;
  item->text.push_back(p);
  for(;;) {
    while( *p && *p!='\n' ) p++;
    if(*p) p++;
    if(*p) item->text.push_back(p);
    else break;
  }
  int firstrow = item->top;
  int diff = item->text.size() - oldsize;
  if( diff )  {
    for( item ++; item!=items.end(); item++ ) item->top += diff;
    item = items.end() - 1;
  }
  else lastrow = item->top + oldsize;
  if( lastrow < item->top + item->text.size() ) lastrow = item->top + item->text.size();

  itemScroll.invalidate( firstrow, lastrow );
  itemScroll.changedSize();
  wrefresh(win);
}

void getTextExtents(const char *text, int &width, int &height )
{
  width = 0;
  height = 0;
  const char *p;
  const char *s;
  p = text;
  do {
    s = p;
    while( *p && *p!='\n' ) p++;
    if(p-s>0) {
      height++;
      if(width<p-s) width=p-s;
    } else if (*p) height++;
    if(*p) p++;
  } while( *p );
}

void drawText( WINDOW *win, const TextBox &b, const char *text, const bool center = false )
{
  int cx,cy;
  const char *p;
  const char *s;
  cx = b.x;
  cy = b.y;
  p = text;
  do {
    s = p;
    while( *p && *p!='\n' ) p++;
    int len = p-s;
    if(len && cy<b.y+b.h ) {
      int offset = center ? (b.w - cx - len) / 2 : 0;
      int res = mvwaddnstr( win, cy, cx + offset, s, len);
    }
    cy++;
    if(*p) p++;
  } while( *p );
}

void clearBox( WINDOW *win, const TextBox &b ) 
{
  if(b.w==0 || b.h==0 ) return;
  dprintf("clearing: h=%i, w=%i, y=%i, x=%i", b.h, b.w, b.y,b.x);
  WINDOW *w = derwin(win,b.h,b.w,b.y,b.x);
  werase(w);
  touchwin(win);
  wrefresh(w);
  delwin(w);
}

void DynmenuCursesView::notify(Dynmenu *menu, Dynmenu::notify_id id)
{
  int tx,ty, tw,th, oldbottom;
  switch(id) {
  case Dynmenu::TITLE:
    getTextExtents( menu->title(), tw, th );
    tx = 0;
    ty = 0;
    tw = maxx - tx;
    dprintf("tx = %i, ty=%i, title=%s, tw=%i", tx, ty, menu->title(), tw );
    clearBox(win,titleBox);
    oldbottom = titleBox.y+titleBox.h;
    titleBox.update(tx,ty,tw,th);
    if(oldbottom!=titleBox.y+titleBox.h) { 
      notify(menu,Dynmenu::WELCOMETEXT);
    }
    drawText(win,titleBox,  menu->title(), true );
    break;
  case Dynmenu::WELCOMETEXT:
    getTextExtents( menu->welcomeText(), tw, th );
    tx = ( maxx  - tw )/ 2;
    ty = titleBox.y+titleBox.h+2;
    clearBox(win,welcomeBox);
    if(ty+th!=welcomeBox.y+welcomeBox.h) {
      // Need to resize itemsBox
      if(itemwin) {
        werase(itemwin);
        delwin(itemwin);
      }
      itemwin = derwin(win,maxy-ty-th-1,maxx-3, ty+th, 2);
      itemScroll.setWin(itemwin);
    }
    welcomeBox.update(tx,ty,tw,th);
    drawText(win,welcomeBox, menu->welcomeText() );
    //mvwaddstr(win,ty,tx, menu->welcomeText() );
    break;
  case Dynmenu::SELECTION:
    //dprintf("items=%zu, selection=%i", menu->items.size(), menu->selection() );
    int sel=selected;
    selected = menu->selection();
    if(sel!=-1) 
      itemScroll.invalidate(items[sel].top, items[sel].top+items[sel].text.size() );
    sel = selected;
    if(sel!=-1)  {
      itemScroll.invalidate(items[sel].top, items[sel].top+items[sel].text.size() );
      itemScroll.scrollTo(items[sel].top, items[sel].top+items[sel].text.size() );
      wrefresh(itemwin);
    }
    break;
  }
  wrefresh(win);
}

void DynmenuCursesView::show(WINDOW *win)
{
  if( win ) {
    this->win = win;
    getmaxyx(win,maxy,maxx);
    //box(win, 0, 0);
    if(itemwin) { wrefresh(itemwin); }
    wrefresh(win);
  }
  else {
  }
}

#include <string>
#include <cctype>

using std::string;
using std::isspace;

class Parser
{
	int peeked;
  void *gdata;
	int (*getter)(void *);
	int peek() { return peeked==-2 ? (peeked=getter(gdata)) : peeked; }
	int get() { int retv =  peeked==-2? (peeked=getter(gdata)) : peeked; peeked=-2; return retv;}
	bool peekedSpace() { return isspace(peek()); }
	void skipSpace() { while(peekedSpace()) get(); }
public:
	enum tokentype { Identifier, String, EOL };
	enum exception { NoGetter, SyntaxError };
	void setCharGetter( int (*g)(void*), void *user ) { getter=g; gdata=user; }
	void expect( tokentype t, std::string &s );
	Parser() : peeked(-2), getter(NULL), gdata(NULL) {}
};

void Parser::expect( tokentype t, std::string &s )
{
	if(! getter ) throw NoGetter;

	int c;

	switch( t ) {
	case Identifier:
		skipSpace();
		s = "";
		while( peek()!=-1 && ! peekedSpace() ) s += (char)get() ;
		break;
	case String:
		skipSpace();
		s = "";
		if( peek() !='"' ) throw SyntaxError;
		get(); // peel off open-quote
		while(peek()!='"' && peek()!=-1 ) {
			c = get();
			if( c=='\\')  {
        c=get(); // allow escaped quotes
        if(c=='n') c='\n';
        else if(c=='t') c='\t';
      }
			s += (char)c ;
		}
		get(); // peel off close-quote
		break;
	case EOL:
		while( peek()!=-1 && isspace(peek()) && peek()!='\n' ) get();
		if( !isspace(peek()) ) throw SyntaxError;
		break;
	}
}




#include <sys/select.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>

#define CTRLL 12


int buf_getc( const char **p )
{
  if(**p) return *((*p)++);
  else return -1;
}

void trap_signals()
{
  struct sigaction s;
  s.sa_handler = SIG_IGN;
  int sig[] = { SIGINT, SIGTSTP, SIGQUIT, };
  for (int i=0; i<sizeof(sig)/sizeof(sig[0]); ++i)
    sigaction(sig[i], &s, 0);
}

void bye(void) { if (!isendwin()) endwin(); }

int main(int argc, char **argv)
{
  // char buf1[3]; strcpy(buf1, "joehere"); printf("buf=\"%s\"\n");
  if (argc != 2) {
    fputs("usage: dynmenu socket-file\n", stderr);
    return 1;
  }

  trap_signals();

  Dynmenu menu;

//#define SIMPLE
#ifdef SIMPLE
  DynmenuSimpleView view;
#else
  DynmenuCursesView view;
  WINDOW *win = initscr();
  atexit(bye);
  curs_set(0); cbreak(); noecho(); keypad(stdscr, 1);
  wclear(win);
  view.show(win);
#endif
  menu.registerView( &view );
  int fd;

  fd_set fds;
  int res;
  if ((fd = open((const char *) argv[1], O_RDWR|O_NONBLOCK)) < 0) {
    perror("error opening socket-file");
    return 1;
  }
  FILE *fifo;
  if ((fifo = fdopen(fd, "r")) == NULL) {
    perror("error opening socket-file: fdopen");
    return 1;
  }

  FD_ZERO(&fds); FD_SET(fd, &fds); FD_SET(0, &fds);
top:
  /* Note: On terminal resize, select returns -1 and sets errno to EINTR */
  dprintf("mainloop...");
  while ((res = select(fd+1, &fds, NULL, NULL, NULL)) >= 0)
  {
    if (FD_ISSET(0, &fds)) {
      //dprintf("char !");//space!");
      int c = getch();
      if (c == ERR) {
        perror("error reading stdin");
        return 1;
      }
      switch (c) {
        case KEY_UP:   case 'k': menu.cursorUp();   break;
        case KEY_DOWN: case 'j': menu.cursorDown(); break;
        case KEY_RIGHT: case '\n': case '\x0d': case 'l':
        case KEY_ENTER: 
          if (!menu.haveSelection())
            break;
          bye();
          endwin();
          execl("/bin/sh", "/bin/sh", "-c", menu.selectedCommand(), (char *) NULL);
          perror("exec failed");
          exit(1); 
          break;

        case 'Q': bye(); endwin(); exit(0); break;

#ifndef SIMPLE
        case 'r':
        case CTRLL:  menu.redraw(); break;
#endif
/*
        case ' ':
          {
            dprintf("space!");
            static char b = 'A';
            char buf[80]; sprintf( buf, "Letter '%c'", b++ );
            menu.setItem( "id3", "3", buf, "id3 cmd");
          }
*/
          break;
      }
    }
    if (FD_ISSET(fd, &fds)) {
      Parser *p = new Parser;
      char line[1024];//[PIPE_BUF];
      assert(line);
      char *pointer = line;
      while (fgets(line, 1024, fifo) != NULL) {
        dprintf("%s", line );
        try {
          pointer = line;
          string menuMethod(1024,' ');
          string id(1024, ' '); string sortkey(1024, ' ');
          string desc(1024, ' '); string cmd(1024, ' '); string dummy;
          p->setCharGetter( (int (*)(void*))buf_getc, (void*)&pointer );
          p->expect( Parser::Identifier, menuMethod );
          if( menuMethod=="setItem" ) {
            p->expect( Parser::String, id );
            p->expect( Parser::String, sortkey );
            p->expect( Parser::String, desc );
            p->expect( Parser::String, cmd );
            menu.setItem( id.c_str(), sortkey.c_str(), desc.c_str(), cmd.c_str() );
          }
          else if( menuMethod=="setTitle" ) {
            p->expect( Parser::String, desc );
            menu.setTitle( desc.c_str() );
          }
          else if( menuMethod=="setWelcomeText" ) {
            p->expect( Parser::String, desc );
            menu.setWelcomeText( desc.c_str() );
          }
          else if( menuMethod=="delItem" ) {
            p->expect( Parser::String, id );
            menu.delItem( id.c_str() );
          }
          else if( menuMethod=="selectItem" ) {
            p->expect( Parser::String, id );
            menu.selectItem( id.c_str() );
          }
        } 
        catch(...) {
          dprintf("exception");
        }
      }
    }
    FD_ZERO(&fds); 
    if (!feof(fifo)) // will never eof if it is a fifo
      FD_SET(fd, &fds); // could use inotify here...
    FD_SET(0, &fds);
  }
  char ebuf[80] ="";
  switch(errno) 
  {
    case EINTR:
      menu.redraw();
      goto top;
    case EBADF: strcpy(ebuf, "EBADF"); break;
    case EINVAL: strcpy(ebuf, "EINVAL"); break;
    case ENOMEM: strcpy(ebuf, "ENOMEM"); break;
    default: sprintf(ebuf, "0x%X", errno);
  }
  endwin();
  printf("  errno = %s\n", ebuf );

  return 0;
}

// vim:ts=2 sw=2 et: