File: AlignmentWidget.cpp

package info (click to toggle)
clustalx 2.1%2Blgpl-8
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 3,320 kB
  • sloc: cpp: 40,050; sh: 163; xml: 102; makefile: 16
file content (1129 lines) | stat: -rw-r--r-- 37,796 bytes parent folder | download | duplicates (2)
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
/**
 * @author Mark Larkin, Conway Institute, UCD. mark.larkin@ucd.ie
 * The AlignmentWidget is used to display a multiple alignment. It takes sequences
 * in the form of QString objects. The conservation information is displayed,
 * if it is available.
 *
 * Changes:
 *
 * 18-12-06,Nigel Brown(EMBL): calcConserveInfo(): removed decrement by 2
 * of maxAA, since this is already done by the owner class; simplified a
 * few l-value expressions.
 *
 * 16-01-07,Nigel Brown(EMBL): added drawContents() called by paintEvent().
 *
 * 31-01-07,Nigel Brown(EMBL): changed && to || in changeBoxSizeAndFontSize().
 *
 * 03-02-07,Nigel Brown(EMBL): changed pencolor to white for
 * lowScoreColoredRes and exceptionalColoredRes in generatePixMaps()
 * in keeping with 'clustalX'.
 *
 * 06-02-07,Nigel Brown(EMBL): darker low scoring and exceptional residues for
 * Mac.
 *
 * 20-02-07,Nigel Brown(EMBL): constructor and changeBoxSizeAndFontSize()
 * parameters reordered.
 *
 * 12-4-07, Mark Larkin, Removed destructor. No need to delete QObjects.
 *
 * 25-04-07,Nigel Brown(EMBL): Removed keyPressEvent(), keyReleaseEvent(),
 * shiftPressed. Keyboard events handled by KeyController singleton. Fixed
 * problem in shift-selection of columns which did not extend selection
 * backwards by replacing with new procedure selectColumns().
 *
 * 04-05-07,Nigel Brown(EMBL): moved getFirstSelectedCol() and
 * getSecondSelectedCol() in from include file; modified them to ensure they
 * return low-to-high ordered values, regardless of the actual mouse selection
 * ordering.
 *
 * 09-05-07,Nigel Brown(EMBL): added ensureVisible() call on new
 * 'scrollArea' member inside mouseMoveEvent() to scroll when column
 * range selection extends beyond visible.
 *
 * 2007-12-03, Andreas Wilm (UCD): removed nigels comments from
 * include line to avoid compiler warnings
 *
 ****************************************************************************/

#include <QtWidgets>
#include "AlignmentWidget.h"
#include "clustalW/general/userparams.h"
#include "ClustalQtParams.h"
#include "KeyController.h"
// KeyController.h - nige
//AW not needed anymore#include "compile.h"
//#include <iostream>
//using namespace std;

/**
 * This is the constructor for an AlignmentWidget.
 * @param num The number of sequences to be displayed in the AlignmentWidget.
 * @param length The length of the alignment.
 * @param boxsize The size of the box to be used in displaying one residue.
 * @param *parent The parent widget of this widget, an optional parameter.
 */
AlignmentWidget::AlignmentWidget(int boxwidth, int boxsize, QFont* font, QWidget *parent)
    : QWidget(parent),
      blackAndWhite(false),
      selectedColoredRes(0),
      lowScoreColoredRes(0),
      exceptionalColoredRes(0),
      conservationPixmaps(0),
      secStructPixmaps(0),
      backGroundColor(true),
      secStruct(0),
      defaultIndex(0)
{
    setEnabled(true);
    setFocusPolicy(Qt::StrongFocus);

    defaultPixMap.fill(Qt::white);
    exResLoaded = false;
    showExceptionalRes = false;
    lowScoreResLoaded = false;
    showLowScoreRes = false;
    defaultColor = QColor(Qt::white);
    secStructInfo = "";   
    alignment = 0;
    firstSeq = 0;
    lastSeq = 0;
    exceptionalRes = 0;
    lowScoreRes = 0;
    colorAlignment = 0;
    /*
     * Set up initial values
     */
    firstColumnSelected = -1;
    secondColumn = -1;
    setMouseTracking(true);
    boxSize = boxsize;
    boxWidth = boxwidth;
    defaultPixMap = QPixmap(boxWidth, boxSize);
    defaultPixMap.fill();  
    offSetFromTop = 2;
    displayStartPos = 0;

    conserveDisplay = false;
    mousePressed = false;
    alignmentSet = false;
    showAlignment = false;
    displayFont = *font;

    alignLength = 0;
    numSequencesSoFar = 0;
    /*
     * Set up the colors to be used in displaying the alignment
     */
    selectedColor = new QColor;
    lightGrey = new QColor;
    slateGrey = new QColor;
    backGroundGrey = new QColor;
   
    selectedColor->setRgb(197, 197, 226);
#if OS_MAC
    lightGrey->setRgb(112, 112, 112);
    slateGrey->setRgb(60, 60, 60);
#else
    lightGrey->setRgb(211, 211, 211);
    slateGrey->setRgb(112, 128, 144);
#endif
    backGroundGrey->setRgb(221, 221, 221);
    setUpWeakAndStrongGroups();
   
    conservationChars = " .:*";   
}

void AlignmentWidget::setAlignment(const clustalw::SeqArray* align,
                                   clustalw::Alignment* _alignObjPtr)
{
    alignment = align;
    alignObjPtr = _alignObjPtr;
    alignmentSet = true;
    firstSeq = 0;
    lastSeq = 0;
    numSequencesSoFar = 0;
   
    colorAlignment = new clustalw::Array2D<QPixmap*>;
    selectedColoredRes = new std::vector<QPixmap>;
    lowScoreColoredRes = new std::vector<QPixmap>;
    exceptionalColoredRes = new std::vector<QPixmap>;
    conservationPixmaps = new std::vector<QPixmap>;
    secStructPixmaps = new std::vector<QPixmap>;
   
    calcConserveInfo();
    updateSizeHint();
}

void AlignmentWidget::updateDisplay(int fSeq, int lSeq, clustalw::Array2D<int>* exRes,
                                    int nhead, QString secStructString)
{
    if(fSeq != 0 && lSeq != 0)
    {
        lowScoreResLoaded = false;
        showLowScoreRes = false;
        alignmentSet = true;
        showAlignment = true;
        exResLoaded = true;
        firstSeq = fSeq;
        lastSeq = lSeq;
        numSequencesSoFar = lastSeq - firstSeq + 1;
        secStruct = nhead;
        secStructInfo = secStructString;
        updateSizeHint();
        calcConserveInfo();
        exceptionalRes = exRes;
        calculatePixMaps();
        firstColumnSelected = -1; // dont show previous selection
        secondColumn = -1;       
    }
    else
    {
        firstSeq = 0;
        lastSeq = 0;
        alignmentSet = false;
        showAlignment = false;
        lowScoreResLoaded = false;
        showLowScoreRes = false;       
        exResLoaded = false;
        secStruct = 0;
        secStructInfo = "";       
        colorAlignment->clearArray();
        //selectedColoredRes->clear();
        numSequencesSoFar = 0;
        firstColumnSelected = -1;
        secondColumn = -1;
        updateSizeHint();      
    }
    update();
}

void AlignmentWidget::calculatePixMaps()
{
    int lengthLongestSeq = alignObjPtr->getLengthLongestSequence(firstSeq,lastSeq);
    std::map<char, QColor*>::iterator colorIterator;
    QFontMetrics fontMetrics(displayFont);
   
    colorAlignment->clearArray();
    colorAlignment->ResizeRect(numSequencesSoFar + getExtraRowNum(), lengthLongestSeq + 1);  
    makeColorMask(&colMask, currentColorScheme);

    int extraRow = getExtraRowNum();
    int currentSeq;       
    char currentChar;
    int codeForAA;
    int colorRow;
    int codeForSpace = clustalw::userParameters->resIndex(
                                          clustalw::userParameters->getAminoAcidCodes(), '-');
    if(secStruct == 1)
    {
        generateSecStructurePixmaps();
    }
                                         
    for(int i = 0; i < colorAlignment->getRowSize(); i++)
    {
        currentSeq = firstSeq + i - extraRow;
        for(unsigned int j = 0; j < lengthLongestSeq; j++)
        {
            (*colorAlignment)[i][j] = &defaultPixMap;                              

            if(i == 0)
            {
                // Conservation information.
                currentChar = conservationInfo[j];
                int code = clustalw::userParameters->resIndex(conservationChars, currentChar);
               
                if(code >= 0 && code < conservationPixmaps->size())
                {
                    (*colorAlignment)[i][j] = &(*conservationPixmaps)[code];
                }
                else
                {
                    (*colorAlignment)[i][j] = &defaultPixMap;
                }
            }
            else if(i == 1 && secStruct == 1)
            {
                (*colorAlignment)[i][j] = &(*secStructPixmaps)[j];
            }
            else
            {
                if((*alignment)[currentSeq].size() > j + 1)
                {
                    codeForAA = (*alignment)[currentSeq][j + 1];
                    if(codeForAA == 31 || codeForAA == 30)
                    {
                        char res = '-';
                        codeForAA = clustalw::userParameters->resIndex(
                                         clustalw::userParameters->getAminoAcidCodes(), res);
                    }
                }
                else
                {
                    codeForAA = -1;
                }               
               
                if(lowScoreResLoaded && showLowScoreRes &&
                  (*lowScoreRes)[currentSeq - firstSeq][j] == 1)
                {
                    if(codeForAA >=0 && codeForAA < lowScoreColoredRes->size())
                    {              
                        (*colorAlignment)[i][j] = &(*lowScoreColoredRes)[codeForAA];
                    }
                    else
                    {
                        (*colorAlignment)[i][j] = &defaultPixMap;
                    }                    
                }
                else if(showExceptionalRes && exResLoaded &&
                       (*exceptionalRes)[currentSeq - firstSeq][j] == 1)
                {
                    if(codeForAA >=0 && codeForAA < exceptionalColoredRes->size())
                    {              
                        (*colorAlignment)[i][j] = &(*exceptionalColoredRes)[codeForAA];
                    }
                    else
                    {
                        (*colorAlignment)[i][j] = &defaultPixMap;
                    }
                }
                else
                {
                    if(colMask.getRowSize() > (i - extraRow) && colMask.getColSize() > j)
                    {
                        if(blackAndWhite)
                        {
                            colorRow = 0;
                        }
                        else
                        {
                            colorRow = colMask[i - extraRow][j];
                        }
                    }
                    else
                    {
                        colorRow = 0; // default
                    }
                    if(colorRow >= 0 && colorRow < coloredLetters.getRowSize() &&
                       codeForAA >=0 && codeForAA < coloredLetters.getColSize())
                    {              
                        (*colorAlignment)[i][j] = &coloredLetters[colorRow][codeForAA];
                    }
                    else
                    {
                        (*colorAlignment)[i][j] = &defaultPixMap;
                    }                   
                }
            }
        }
    }
    update();
}

void AlignmentWidget::generateSecStructurePixmaps()
{
    QFontMetrics fontMetrics(displayFont);
    int lengthLongestSeq = alignObjPtr->getLengthLongestSequence(firstSeq,lastSeq);
    secStructPixmaps->clear();
    secStructPixmaps->resize(lengthLongestSeq + 1);
    defaultGreyPixMap = QPixmap(boxWidth, boxSize);
    defaultGreyPixMap.fill(backGroundGrey->rgb());
      
    for(int i = 0; i < secStructInfo.size(); i++)
    {
        if(i < secStructPixmaps->size() && i < secStructInfo.size())
        {
            displayFont.setBold(true);          
               
            // secondary structure info
            (*secStructPixmaps)[i] = defaultGreyPixMap;
            (*secStructPixmaps)[i].fill(backGroundGrey->rgb());
           
            QPainter paintChar(&(*secStructPixmaps)[i]);
            paintChar.setFont(displayFont);                        
            paintChar.drawText((boxWidth / 2) -
                fontMetrics.width(secStructInfo[i])/2,
                offSetFromTop + fontMetrics.ascent(),
                QString(secStructInfo[i]));
        }
    }
}

void AlignmentWidget::showLowScoreSeg(bool show, clustalw::Array2D<int>* _lowScoreRes)
{
    int numSeqs = lastSeq - firstSeq + 1;
    if(_lowScoreRes != 0)
    {
        if((_lowScoreRes->getRowSize() == numSeqs + 1) &&
           (_lowScoreRes->getColSize() == alignObjPtr->getLengthLongestSequence(firstSeq,
                                                                             lastSeq) + 1))
        {
            lowScoreRes = _lowScoreRes;
            lowScoreResLoaded = true;
            showLowScoreRes = show;
        }
    }
    else
    {
        lowScoreResLoaded = false;
        showLowScoreRes = false;
    }
    calculatePixMaps();
    update();
}

/**
 * The function sizeHint is overloaded from the QWidget class. It gives a recomended size for
 * the widget when resizing is performed.
 */
QSize AlignmentWidget::sizeHint() const
{
    int extraRow;
    if(secStruct == 1)
    {
        extraRow = 2;
    }
    else
    {
        extraRow = 1;
    }
    return QSize(alignLength * boxWidth, (numSequencesSoFar + extraRow) * boxSize);
}

void AlignmentWidget::showExceptionalResidues(bool show)
{
    showExceptionalRes = show;
    calculatePixMaps();
    update();
}

/**
 * This function is an event handler. It finds the column in the alignment
 * that has been clicked.
 * @param *event A mouse event.
 */
void AlignmentWidget::mousePressEvent(QMouseEvent *event)  //nige
{
    KeyController *kbd = KeyController::Instance();

    if (event->button() == Qt::LeftButton) {
        mousePressed = true;

        int column = (event->x() / boxWidth);
        if (kbd->shiftPressed()) {
            selectColumns(column);
        } else {
            firstColumnSelected = column;
            secondColumn = -1;
        }
        update(); //nige
        return;
    }
    QWidget::mousePressEvent(event);
}

/**
 * This function is an event handler. It finds the column in the alignment that the mouse
 * is at when the mouse button has been released.
 * @param *event A mouse event.
 */
void AlignmentWidget::mouseReleaseEvent(QMouseEvent *event)  //nige
{
    if (event->button() == Qt::LeftButton) {
        mousePressed = false;
        update();
        return;
    }
    QWidget::mouseReleaseEvent(event);
}

void AlignmentWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (mousePressed == true) {

        //scroll if necessary to continue selection
        scrollArea->ensureVisible(event->x(), event->y());

        int column = (event->x() / boxWidth);
        secondColumn = column;
        update();
        return;
    }
    QWidget::mouseMoveEvent(event);
}

void AlignmentWidget::selectColumns(int column) {
    //cout << "setCols(IN  " << firstColumnSelected << "," << secondColumn << ")\n";
    bool growright = true;

    if (secondColumn == -1) {
        if (column < firstColumnSelected)
            growright = false;
        secondColumn = firstColumnSelected;
    } else if (firstColumnSelected > secondColumn) {
        growright = false;
    }

    if (growright) {
        if (column < firstColumnSelected) {
            //reverse direction
            // c < f <= s ---> f<=>s then c < f
            firstColumnSelected = secondColumn;
            secondColumn = column;
        } else if (column > secondColumn) {
            // f <= s < c ---> f < s
            secondColumn = column;
        } else {
            // f (c) s    ---> f < c
            secondColumn = column;
        }
    } else {//growleft
        if (column < secondColumn) {
            // c < s < f ---> c < f
            secondColumn = column;
        } else if (column > firstColumnSelected) {
            //reverse direction
            // s < f < c ---> f<=>s then f < c
            firstColumnSelected = secondColumn;
            secondColumn = column;
        } else {
            // s (c) f   ---> c < f
            secondColumn = column;
        }
    }
    //cout << "setCols(OUT " << firstColumnSelected << "," << secondColumn << ")\n";
}

/**
 * This function will be called every time sequences are changed. So for example after
 * an alignment, after we add more sequences etc
 */
void AlignmentWidget::updateSizeHint()
{
    int lengthLongest = alignObjPtr->getLengthLongestSequence(firstSeq, lastSeq);
    int extraRow = getExtraRowNum();
    resize(lengthLongest * boxWidth,
          (numSequencesSoFar + extraRow) * boxSize);
}

/**
 * This function is an event handler. It repaints the widget whenever it needs
 * to be repainted. It is called automatically.
 * It also calculates the number of columns showing and colors in the alignment.
 * @param *event A resize event.
 */
void AlignmentWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QRect rect = event->rect();
    int cx = rect.x();
    int cy = rect.y();
    int cw = rect.width();
    int ch = rect.height();
    //(void) printf("paintEvent(%d,%d, %d,%d)\n", cx,cy, cw,ch);
    drawContents(&painter, cx, cy, cw, ch);
}

void AlignmentWidget::drawContents(QPainter *painter, int cx, int cy, int cw, int ch)
{
    painter->fillRect(cx, cy, cw, ch, QBrush(Qt::green));//white));
    painter->setBackgroundMode(Qt::OpaqueMode);
    
    // Set up the begin and end columns and rows. 
    int beginRow    = cy        / boxSize;
    int beginColumn = cx        / boxWidth;
    int endRow      = (cy+ch-1) / boxSize;
    int endColumn   = (cx+cw-1) / boxWidth;

    int selectedRes;
    conserveDisplay = true;
    int seqLength = 0;
    int extra = getExtraRowNum();
    
    //(void) printf("drawContents(x=%d,y=%d, w=%d,h=%d)(bw=%d,bh=%d) -> [br=%d,er=%d, bc=%d,ec=%d]\n",
                  //cx,cy, cw,ch, boxWidth, boxSize, beginRow,endRow, beginColumn,endColumn);

    if(firstSeq != 0 && alignmentSet && showAlignment)
    {
        for (int row = beginRow; row <= endRow; ++row) 
        {
            for (int column = beginColumn; column <= endColumn; ++column) 
            {
                //printf("draw[0](%d,%d)\n", row, column);

                if(firstSeq + row - extra >= 1)
                {
                    seqLength = alignObjPtr->getSeqLength(firstSeq + row - extra);
                }
                else
                {
                    seqLength = 0;
                }

                if (row > (extra - 1) && column < seqLength && 
                (((column >= firstColumnSelected) && (column <= secondColumn))
                    || ((column >= secondColumn) && (column <= firstColumnSelected) &&
                          secondColumn != -1))) // Selected ???? 
                {
                    selectedRes = (*alignment)[firstSeq + row - extra][column + 1];
                    
                    if(selectedRes >= selectedColoredRes->size())
                    {
                        selectedRes = selectedColoredRes->size() - 1; // '-'
                    }
                    if(selectedRes >= 0 && !(*selectedColoredRes)[selectedRes].isNull())
                    {
                        //printf("draw[1](%d,%d)\n", row, column);

                        painter->drawPixmap((column) * boxWidth, row * boxSize,
                                            (*selectedColoredRes)[selectedRes]);
                    }  
                }                    
                else
                {
                    // NOTE we need to have this check here. It was causing problems
                    // when removing gaps sometimes. Seems to be ok now!!! 
                    if(row < colorAlignment->getRowSize() && row >= 0 &&
                       column < colorAlignment->getColSize() && column >= 0)
                    {
                        //printf("draw[2](%d,%d) [%d,%d]\n", row, column,
                        //       colorAlignment->getRowSize(),
                        //       colorAlignment->getColSize()
                         //   );
                
                        if(!(*colorAlignment)[row][column]->isNull())
                        {
                            //printf("draw[3](%d,%d) [%d,%d]\n", row, column,
                            //       colorAlignment->getRowSize(),
                            //       colorAlignment->getColSize()
                            //    );
                            painter->drawPixmap((column) * boxWidth, 
                                                row * boxSize,*(*colorAlignment)[row][column]);
                        }
                    }
                }
            }
        }
    }
}

void AlignmentWidget::changeBoxSizeAndFontSize(int _boxWidth, int _boxSize, QFont* fontPtr)
{
    if (boxWidth != _boxWidth || boxSize != _boxSize) //nige: changed && to ||
    {       
        boxWidth = _boxWidth;
        boxSize  = _boxSize;
        displayFont = *fontPtr;
        int lengthLongest = alignObjPtr->getLengthLongestSequence(firstSeq, lastSeq);
        resize(lengthLongest * boxWidth, (numSequencesSoFar + 1) * boxSize);
        defaultPixMap = QPixmap(boxWidth, boxSize);
        defaultPixMap.fill(Qt::white);
        generatePixMaps();
        calculatePixMaps();   
        repaint();
    }
}

/**
 * This is a wrapper for the function in the clustalw code.
 */
char AlignmentWidget::getAminoAcidCode(int i)
{
    if(i < 0 || i >= clustalw::userParameters->getMaxAA())
    {
        return '-';
    }
    return clustalw::userParameters->getAminoAcidCode(i);
}

void AlignmentWidget::setUpWeakAndStrongGroups()
{
    strongGroup.resize(9);
    strongGroup[0] = string("STA");
    strongGroup[1] = string("NEQK");
    strongGroup[2] = string("NHQK");
    strongGroup[3] = string("NDEQ");
    strongGroup[4] = string("QHRK");
    strongGroup[5] = string("MILV");
    strongGroup[6] = string("MILF");
    strongGroup[7] = string("HY");
    strongGroup[8] = string("FYW");
   
    weakGroup.resize(11);
    weakGroup[0] = string("CSA");
    weakGroup[1] = string("ATV");
    weakGroup[2] = string("SAG");
    weakGroup[3] = string("STNK");
    weakGroup[4] = string("STPA");
    weakGroup[5] = string("SGND");
    weakGroup[6] = string("SNDEQK");
    weakGroup[7] = string("NDEQHK");
    weakGroup[8] = string("NEQHRK");
    weakGroup[9] = string("FVLIM");
    weakGroup[10] = string("HFY");
}

void AlignmentWidget::calcConserveInfo()
{
    if(firstSeq != 0 && lastSeq != 0)
    {
        int catident1[clustalw::NUMRES];
        int catident2[clustalw::NUMRES];
        int _fSeq, _lSeq;
        int _fRes, _lRes;   
        _fSeq = firstSeq;
        _lSeq = lastSeq;
        _fRes = 1;
        _lRes = alignObjPtr->getLengthLongestSequence(_fSeq, _lSeq);
   
        conservationInfo.clear();
        conservationInfo.resize(_lRes);
   
        int ident;
        char c;

        for(int i = _fRes; i <= _lRes; ++i)
        {
            conservationInfo[i - 1] = ' ';
            ident = 0;

            for(int j = 1; j <= strongGroup.size(); j++)
            {
                catident1[j - 1] = 0;
            }
            for(int j = 1; j <= weakGroup.size(); j++)
            {
                catident2[j - 1] = 0;
            }
               
            for(int j = _fSeq; j <= _lSeq; ++j)
            {
                if((i + _fRes - 1 < (*alignment)[j].size()) &&
                   (i + _fRes - 1 < (*alignment)[_fSeq].size()))
                {
                    /* nige,18-12-06: maxAA already decremented in UserParameters;
                     * introduce some locals for readability
                     */
                    //if(((*alignment)[_fSeq][i + _fRes - 1] >= 0) &&
                    //      ((*alignment)[_fSeq][i + _fRes - 1]
                    //      <= clustalw::userParameters->getMaxAA() - 2))
                    //    Fowler, my ar*e... introduce some locals
                    int thisRes = (*alignment)[_fSeq][i + _fRes - 1];
                    int maxAA = clustalw::userParameters->getMaxAA();

                    if (thisRes >= 0 && thisRes <= maxAA)
                    {
                        // Count how many are identical to the first sequence
                        /* nige,18-12-06 */
                        //if((*alignment)[_fSeq][i + _fRes - 1] ==
                        //    (*alignment)[j][i + _fRes - 1])
                        if(thisRes == (*alignment)[j][i + _fRes - 1])
                 /* nige,end */
                        {
                            ++ident;
                        }
                        // Count how many are in the same category.
                        for(int k = 1; k <= strongGroup.size(); k++)
                        {
                            for(int l = 0; (c = strongGroup[k - 1][l]); l++)
                            {
                                int resCode = (*alignment)[j][i + _fRes - 1];
                                if (getAminoAcidCode(resCode) == c)
                                {
                                    catident1[k - 1]++;
                                    break;
                                }
                            }
                        }
                        for(int k = 1; k <= weakGroup.size(); k++)
                        {
                            for(int l = 0; (c = weakGroup[k - 1][l]); l++)
                            {
                                int resCode = (*alignment)[j][i + _fRes - 1];
                                if (getAminoAcidCode(resCode) == c)
                                {
                                    catident2[k - 1]++;
                                    break;
                                }
                            }
                        }
                    }
                }   
            }
           
            // Now do the conservation part for each block.
            if(ident == _lSeq - _fSeq + 1)
            {
                conservationInfo[i - 1] = '*'; // All residues the same!
            }
            else if (!clustalw::userParameters->getDNAFlag())
            {
                for(int k = 1; k <= strongGroup.size(); k++)
                {
                    if (catident1[k - 1] == _lSeq - _fSeq + 1)
                    {
                        // All residues member of the same category
                        conservationInfo[i - 1] = ':';
                        break;
                    }
                }
                if(conservationInfo[i - 1] == ' ')
                {
                    for(int k = 1; k <= weakGroup.size(); k++)
                    {
                        if (catident2[k - 1] == _lSeq - _fSeq + 1)
                        {
                            // All residues member of the same category
                            conservationInfo[i - 1] = '.';
                            break;
                        }
                    }
                }
            }
        }
        conserveDisplay = true;
    }
}

void AlignmentWidget::setColorScheme(ColorParameters* colors)
{
    currentColorScheme = colors;
    blackAndWhite = false;
    generatePixMaps();
    if(alignmentSet && showAlignment)
    {
        calculatePixMaps();
    }
}   

void AlignmentWidget::setPrintoutColorScheme(ColorParameters colors)
{
    printoutColorScheme = colors;
}

void AlignmentWidget::setBlackAndWhite()
{
    blackAndWhite = true;
    if(alignmentSet && showAlignment)
    {
        generatePixMaps();
        calculatePixMaps();
    }
}

void AlignmentWidget::setBackGroundColoring(bool _backGroundColor)
{
    backGroundColor = _backGroundColor;
    if(alignmentSet && showAlignment)
    {
        generatePixMaps();
        calculatePixMaps();
    }
}

void AlignmentWidget::makeColorMask(clustalw::Array2D<QColor>* colMask,
                                    ColorParameters* colorScheme)
{
    QColor defaultColor = currentColorScheme->getDefaultColor();
   
    int lengthLongest = alignObjPtr->getLengthLongestSequence(firstSeq, lastSeq);
   
    colMask->clearArray();
    colMask->ResizeRect(numSequencesSoFar, lengthLongest);
    clustalw::Array2D<int> intColMask;
    makeColorMask(&intColMask, colorScheme);
   
    for(int i = 0; i < colMask->getRowSize(); i++)
    {
        for(int j = 0; j < colMask->getColSize(); j++)
        {
            if(i < intColMask.getRowSize() && j < intColMask.getColSize())
            {
                (*colMask)[i][j] = colorScheme->getColorFromNum(intColMask[i][j]);
            }
            else
            {
                (*colMask)[i][j] = defaultColor;
            }
        }
    }
}

void AlignmentWidget::makeColorMask(clustalw::Array2D<int>* colMask,
                                    ColorParameters* colorScheme)
{  
    int lengthLongest = alignObjPtr->getLengthLongestSequence(firstSeq, lastSeq);
   
    colMask->clearArray();
    colMask->ResizeRect(numSequencesSoFar, lengthLongest);
   
    for(int i = 0; i < colMask->getRowSize(); i++)
    {
        for(int j = 0; j < colMask->getColSize(); j++)
        {
            (*colMask)[i][j] = colorScheme->getDefaultIndex();
        }
    }
    int currentSeq;
    int code;
    QString consensus;
    consensus = initConsensus();
    std::string mystring = consensus.toStdString();
    QChar alignRes;
   
    for(int seq = 0; seq < numSequencesSoFar; seq++)
    {
        currentSeq = firstSeq + seq;
        for(int res = 0; res < lengthLongest; res++)
        {
            if(res + 1 < (*alignment)[currentSeq].size() && (lastSeq >= currentSeq))
            {
                code = (*alignment)[currentSeq][res + 1];
                alignRes = QChar(getAminoAcidCode(code));
            }
            else
            {
                alignRes = QChar('-');
            }
           
            (*colMask)[seq][res] = colorScheme->getResidueColorNum(alignRes,
                                                                   consensus[res]);
            if((*colMask)[seq][res] > colorScheme->getNumColors())
            {
                colorScheme->getResidueColorNum(alignRes, consensus[res]);
            }                                                      
        }
    } 
}

QString AlignmentWidget::initConsensus()
{
    QString consData;
    int numRes, seq, res, par, consTotal, i;
    QChar residue;
    int code;
    int numConsParams = currentColorScheme->getNumConsensusParams();
    int currentSeq;
   
    int lengthLongest = alignObjPtr->getLengthLongestSequence(firstSeq, lastSeq);
   
    std::vector<consensusParams>* consParams = currentColorScheme->getConPar();
   
    consData.resize(lengthLongest + 1);
    for(int j = 0; j < consData.size(); j++)
    {
        consData[j] = ' ';
    }
   
    for(res = 0; res < lengthLongest; res++)
    {
        for(par = 0; par < numConsParams; par++)
        {
            consTotal = numRes = 0;
           
            for(seq = 0; seq < numSequencesSoFar; seq++)
            {
                currentSeq = firstSeq + seq;
               
                if(res + 1 < (*alignment)[currentSeq].size() && (lastSeq >= currentSeq))
                {
                    code = (*alignment)[currentSeq][res + 1];
                    residue = QChar(getAminoAcidCode(code));
                    residue = residue.toLower();
        
                    if(residue.isLetter())
                    {
                        numRes++;
                    }
                    for(i = 0; i < (*consParams)[par].length; i++)
                    {
                        if(residue == (*consParams)[par].cutOffList[i])
                        {
                            consTotal++;
                        }
                    }
                }   
            }
            if(numRes != 0)
            {
                if(((consTotal * 100) / numRes) >= (*consParams)[par].cutOffPercent)
                {
                    consData[res] = (*consParams)[par].consensusName;
                }
            }
        }   
    }
    return consData;
}

void AlignmentWidget::clearRangeSelection()
{
    firstColumnSelected = -1;
    secondColumn = -1;
    update();
}

int AlignmentWidget::getFirstSelectedCol() {
    if (firstColumnSelected < secondColumn)
        return firstColumnSelected;
    else
        return secondColumn;
}

int AlignmentWidget::getSecondSelectedCol() {
    if (firstColumnSelected < secondColumn)
        return secondColumn;
    else
        return firstColumnSelected;
}

int AlignmentWidget::getExtraRowNum()
{
    int extraRow = 1;
    if(secStruct == 1)
    {
        extraRow = 2;
    }
    else
    {
        extraRow = 1;
    }
    return extraRow;
}

void AlignmentWidget::generatePixMaps()
{
    QFontMetrics fontMetrics(displayFont);
    // 0 has the default, colors then, selected = numColors+1,
    std::string aminoAcid = clustalw::userParameters->getAminoAcidCodes();
    int numDiffRes = aminoAcid.size();
    //code = userParameters->resIndex(userParameters->getAminoAcidCodes(), search[i]);
    int numColors = currentColorScheme->getNumColors();
    // number of rows = numColors + white
    int numRows = numColors + 1;
    defaultIndex = 0;
    coloredLetters.clearArray();   
    coloredLetters.ResizeRect(numRows, numDiffRes);
    QColor currentColor;
    // For each of the colors, create the PixMaps
    QColor penColor;
    QBrush boxesBrush;
    char currentChar;
    for(int i = 0; i < numRows; i++)
    {
        if(i == 0)
        {
            currentColor = currentColorScheme->getColorFromNum(i);
            penColor = QColor(Qt::black);
            boxesBrush = QBrush(currentColor.rgb());        
        }
        else if(i <= numColors)
        {
            currentColor = currentColorScheme->getColorFromNum(i);
            if(backGroundColor)
            {
                penColor = QColor(Qt::black);
                boxesBrush = QBrush(currentColor.rgb());
            }
            else
            {
                penColor = currentColor;
                boxesBrush = QColor(Qt::white);
            }           
        }
        else
        {
            currentColor = currentColorScheme->getColorFromNum(0); // default
            penColor = QColor(Qt::black);
            boxesBrush = QBrush(currentColor.rgb());           
        }
        for(int j = 0; j < aminoAcid.size(); j++)
        {
            // get a pen color and a background color!!!!!
            coloredLetters[i][j] = QPixmap(boxWidth, boxSize);
            QPainter paintChar(&coloredLetters[i][j]);           
            coloredLetters[i][j].fill(boxesBrush.color());
           
            currentChar = aminoAcid[j];
           
            paintChar.setFont(displayFont);
            paintChar.setPen(QPen(penColor));
            paintChar.drawText((boxWidth / 2) -
                               fontMetrics.width(currentChar)/2,
                               offSetFromTop + fontMetrics.ascent(),
                               QString(QChar(currentChar)));         
        }
    }
   
    QBrush selectedBrush, exceptionalBrush, lowScoreBrush;
    selectedBrush = QBrush(selectedColor->rgb());
    lowScoreBrush = QBrush(slateGrey->rgb());
    exceptionalBrush = QBrush(lightGrey->rgb());
   
    int length = aminoAcid.size();
    selectedColoredRes->clear();
    selectedColoredRes->resize(length);
    lowScoreColoredRes->clear();
    lowScoreColoredRes->resize(length);
    exceptionalColoredRes->clear();
    exceptionalColoredRes->resize(length);
       
    for(int i = 0; i < length; i++)
    {
        currentChar = aminoAcid[i];
       
        (*selectedColoredRes)[i] = QPixmap(boxWidth, boxSize);
        (*selectedColoredRes)[i].fill(selectedBrush.color());
        QPainter paintChar(&(*selectedColoredRes)[i]);
        paintChar.setFont(displayFont);
        paintChar.drawText((boxWidth / 2) -
                           fontMetrics.width(currentChar)/2,
                           offSetFromTop + fontMetrics.ascent(),
                           QString(QChar(currentChar)));

        (*lowScoreColoredRes)[i] = QPixmap(boxWidth, boxSize);
        (*lowScoreColoredRes)[i].fill(lowScoreBrush.color());
        QPainter paintChar2(&(*lowScoreColoredRes)[i]);
        paintChar2.setFont(displayFont);
        paintChar2.setPen(QPen(QColor(Qt::white)));  //nige
        paintChar2.drawText((boxWidth / 2) -
                           fontMetrics.width(currentChar)/2,
                           offSetFromTop + fontMetrics.ascent(),
                           QString(QChar(currentChar)));
                          
        (*exceptionalColoredRes)[i] = QPixmap(boxWidth, boxSize);
        (*exceptionalColoredRes)[i].fill(exceptionalBrush.color());
        QPainter paintChar3(&(*exceptionalColoredRes)[i]);
        paintChar3.setFont(displayFont);
        paintChar3.setPen(QPen(QColor(Qt::white)));  //nige
        paintChar3.drawText((boxWidth / 2) -
                           fontMetrics.width(currentChar)/2,
                           offSetFromTop + fontMetrics.ascent(),
                           QString(QChar(currentChar)));                                     
    }
   
    QBrush conservationBrush;
    conservationBrush = QBrush(backGroundGrey->rgb());
    int numConserveChars = conservationChars.size();
    conservationPixmaps->resize(numConserveChars);
    displayFont.setBold(true);
               
    for(int i = 0; i < numConserveChars; i++)
    {
        (*conservationPixmaps)[i] = QPixmap(boxWidth, boxSize);       
        (*conservationPixmaps)[i].fill(conservationBrush.color());
        QPainter paintChar(&(*conservationPixmaps)[i]);
        currentChar = conservationChars[i];
        paintChar.setFont(displayFont);       
        paintChar.drawText((boxWidth / 2) -
            fontMetrics.width(currentChar)/2,
            offSetFromTop + fontMetrics.ascent(),
            QString(QChar(currentChar)));
    }          
}

clustalw::Array2D<QColor> AlignmentWidget::getPrintoutColorMask()
{
    clustalw::Array2D<QColor> printoutColorMask;
    makeColorMask(&printoutColorMask, &printoutColorScheme);
    return printoutColorMask;
}