[Bio] / Sprout / SearchHelper.pm Repository:
ViewVC logotype

Diff of /Sprout/SearchHelper.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.14, Wed Nov 8 23:18:24 2006 UTC revision 1.29, Sat Apr 14 21:41:25 2007 UTC
# Line 88  Line 88 
88  TRUE if this is a feature-filtered search, else FALSE. B<NOTE> that this  TRUE if this is a feature-filtered search, else FALSE. B<NOTE> that this
89  field is updated by the B<FeatureQuery> object.  field is updated by the B<FeatureQuery> object.
90    
91    =item extraPos
92    
93    C<0> if the extra columns are to be at the beginning, else C<1>. The
94    default is zero; use the L</SetExtraPos> method to change this option.
95    
96  =back  =back
97    
98  =head2 Adding a new Search Tool  =head2 Adding a new Search Tool
# Line 113  Line 118 
118    
119  =item 4  =item 4
120    
121  In the C<SearchSkeleton.cgi> script, add a C<use> statement for your search tool  In the C<SearchSkeleton.cgi> script and add a C<use> statement for your search tool.
 and then put the class name in the C<@advancedClasses> list.  
122    
123  =back  =back
124    
# Line 231  Line 235 
235  in the output, or you could search for something that's not a feature at all. The  in the output, or you could search for something that's not a feature at all. The
236  above code is just a loose framework.  above code is just a loose framework.
237    
238    In addition to the finding and filtering, it is necessary to send status messages
239    to the output so that the user does not get bored waiting for results. The L</PrintLine>
240    method performs this function. The single parameter should be text to be
241    output to the browser. In general, you'll invoke it as follows.
242    
243        $self->PrintLine("...my message text...<br />");
244    
245    The break tag is optional. When the Find method gets control, a paragraph will
246    have been started so that everything is XHTML-compliant.
247    
248  If you wish to add your own extra columns to the output, use the B<AddExtraColumns>  If you wish to add your own extra columns to the output, use the B<AddExtraColumns>
249  method of the feature query object.  method of the feature query object.
250    
# Line 245  Line 259 
259    
260  # This counter is used to insure every form on the page has a unique name.  # This counter is used to insure every form on the page has a unique name.
261  my $formCount = 0;  my $formCount = 0;
262    # This counter is used to generate unique DIV IDs.
263    my $divCount = 0;
264    
265  =head2 Public Methods  =head2 Public Methods
266    
267  =head3 new  =head3 new
268    
269  C<< my $shelp = SearchHelper->new($query); >>  C<< my $shelp = SearchHelper->new($cgi); >>
270    
271  Construct a new SearchHelper object.  Construct a new SearchHelper object.
272    
273  =over 4  =over 4
274    
275  =item query  =item cgi
276    
277  The CGI query object for the current script.  The CGI query object for the current script.
278    
# Line 266  Line 282 
282    
283  sub new {  sub new {
284      # Get the parameters.      # Get the parameters.
285      my ($class, $query) = @_;      my ($class, $cgi) = @_;
286      # Check for a session ID.      # Check for a session ID.
287      my $session_id = $query->param("SessionID");      my $session_id = $cgi->param("SessionID");
288      my $type = "old";      my $type = "old";
289      if (! $session_id) {      if (! $session_id) {
290            Trace("No session ID found.") if T(3);
291          # Here we're starting a new session. We create the session ID and          # Here we're starting a new session. We create the session ID and
292          # store it in the query object.          # store it in the query object.
293          $session_id = NewSessionID();          $session_id = NewSessionID();
294          $type = "new";          $type = "new";
295          $query->param(-name => 'SessionID', -value => $session_id);          $cgi->param(-name => 'SessionID', -value => $session_id);
296        } else {
297            Trace("Session ID is $session_id.") if T(3);
298      }      }
299      # Compute the subclass name.      # Compute the subclass name.
300      $class =~ /SH(.+)$/;      my $subClass;
301      my $subClass = $1;      if ($class =~ /SH(.+)$/) {
302            # Here we have a real search class.
303            $subClass = $1;
304        } else {
305            # Here we have a bare class. The bare class cannot search, but it can
306            # process search results.
307            $subClass = 'SearchHelper';
308        }
309      # Insure everybody knows we're in Sprout mode.      # Insure everybody knows we're in Sprout mode.
310      $query->param(-name => 'SPROUT', -value => 1);      $cgi->param(-name => 'SPROUT', -value => 1);
311      # Generate the form name.      # Generate the form name.
312      my $formName = "$class$formCount";      my $formName = "$class$formCount";
313      $formCount++;      $formCount++;
# Line 289  Line 315 
315      # as well as an indicator as to whether or not the session is new, plus the      # as well as an indicator as to whether or not the session is new, plus the
316      # class name and a placeholder for the Sprout object.      # class name and a placeholder for the Sprout object.
317      my $retVal = {      my $retVal = {
318                    query => $query,                    query => $cgi,
319                    type => $type,                    type => $type,
320                    class => $subClass,                    class => $subClass,
321                    sprout => undef,                    sprout => undef,
# Line 299  Line 325 
325                    genomeList => undef,                    genomeList => undef,
326                    genomeParms => [],                    genomeParms => [],
327                    filtered => 0,                    filtered => 0,
328                      extraPos => 0,
329                   };                   };
330      # Bless and return it.      # Bless and return it.
331      bless $retVal, $class;      bless $retVal, $class;
# Line 359  Line 386 
386      return ($self->{type} eq 'new');      return ($self->{type} eq 'new');
387  }  }
388    
389    =head3 SetExtraPos
390    
391    C<< $shelp->SetExtraPos($newValue); >>
392    
393    Indicate whether the extra columns should be in the front (C<0>) or end (C<1>) columns of the results.
394    
395    =over 4
396    
397    =item newValue
398    
399    C<1> if the extra columns should be displayed at the end, else C<0>.
400    
401    =back
402    
403    =cut
404    
405    sub SetExtraPos {
406        my ($self, $newValue) = @_;
407        $self->{extraPos} = $newValue;
408    }
409    
410  =head3 ID  =head3 ID
411    
412  C<< my $sessionID = $shelp->ID(); >>  C<< my $sessionID = $shelp->ID(); >>
# Line 453  Line 501 
501      my ($self, $title) = @_;      my ($self, $title) = @_;
502      # Get the CGI object.      # Get the CGI object.
503      my $cgi = $self->Q();      my $cgi = $self->Q();
504      # Start the form.      # Start the form. Note we use the override option on the Class value, in
505        # case the Advanced button was used.
506      my $retVal = "<div class=\"search\">\n" .      my $retVal = "<div class=\"search\">\n" .
507                   $cgi->start_form(-method => 'POST',                   $cgi->start_form(-method => 'POST',
508                                    -action => $cgi->url(-relative => 1),                                    -action => $cgi->url(-relative => 1),
509                                    -name => $self->FormName()) .                                    -name => $self->FormName()) .
510                   $cgi->hidden(-name => 'Class',                   $cgi->hidden(-name => 'Class',
511                                -value => $self->{class}) .                                -value => $self->{class},
512                                  -override => 1) .
513                   $cgi->hidden(-name => 'SPROUT',                   $cgi->hidden(-name => 'SPROUT',
514                                -value => 1) .                                -value => 1) .
515                   $cgi->h3($title);                   $cgi->h3($title);
# Line 659  Line 709 
709      # Check for a first-call situation.      # Check for a first-call situation.
710      if (! defined $self->{cols}) {      if (! defined $self->{cols}) {
711          Trace("Setting up the columns.") if T(3);          Trace("Setting up the columns.") if T(3);
712          # Here we need to set up the column information. Start with the extras,          # Tell the user what's happening.
713            $self->PrintLine("Creating output columns.<br />");
714            # Here we need to set up the column information. First we accumulate the extras,
715          # sorted by column name.          # sorted by column name.
716          my @colNames = ();          my @xtraNames = ();
717          for my $col (sort keys %{$extraCols}) {          for my $col (sort keys %{$extraCols}) {
718              push @colNames, "X=$col";              push @xtraNames, "X=$col";
719            }
720            # Set up the column name array.
721            my @colNames = ();
722            # If extras go at the beginning, put them in first.
723            if (! $self->{extraPos}) {
724                push @colNames, @xtraNames;
725          }          }
726          # Add the default columns.          # Add the default columns.
727          push @colNames, $self->DefaultFeatureColumns();          push @colNames, $self->DefaultFeatureColumns();
728          # Add any additional columns requested by the feature filter.          # Add any additional columns requested by the feature filter.
729          push @colNames, FeatureQuery::AdditionalColumns($self);          push @colNames, FeatureQuery::AdditionalColumns($self);
730            # If extras go at the end, put them in here.
731            if ($self->{extraPos}) {
732                push @colNames, @xtraNames;
733            }
734            Trace("Full column list determined.") if T(3);
735          # Save the full list.          # Save the full list.
736          $self->{cols} = \@colNames;          $self->{cols} = \@colNames;
737          # Write out the column headers. This also prepares the cache file to receive          # Write out the column names. This also prepares the cache file to receive
738          # output.          # output.
739          $self->WriteColumnHeaders(map { $self->FeatureColumnTitle($_) } @{$self->{cols}});          Trace("Writing column headers.") if T(3);
740            $self->WriteColumnHeaders(@{$self->{cols}});
741            Trace("Column headers written.") if T(3);
742      }      }
743      # Get the feature ID.      # Get the feature ID.
744      my $fid = $fd->FID();      my $fid = $fd->FID();
745      # Loop through the column headers, producing the desired data.      # Loop through the column headers, producing the desired data. The first column
746      my @output = ();      # is the feature ID. The feature ID does not show up in the output: its purpose
747        # is to help the various output formatters.
748        my @output = ($fid);
749      for my $colName (@{$self->{cols}}) {      for my $colName (@{$self->{cols}}) {
750          push @output, $self->FeatureColumnValue($colName, $record, $extraCols);          push @output, $self->FeatureColumnValue($colName, $record, $extraCols);
751      }      }
# Line 767  Line 834 
834          # We found one, so close it.          # We found one, so close it.
835          Trace("Closing session file.") if T(2);          Trace("Closing session file.") if T(2);
836          close $self->{fileHandle};          close $self->{fileHandle};
837            # Tell the user.
838            my $cgi = $self->Q();
839            $self->PrintLine("Output formatting complete.<br />");
840      }      }
841  }  }
842    
# Line 946  Line 1016 
1016    
1017  =head3 ComputeFASTA  =head3 ComputeFASTA
1018    
1019  C<< my $fasta = $shelp->ComputeFASTA($incomingType, $desiredType, $sequence); >>  C<< my $fasta = $shelp->ComputeFASTA($desiredType, $sequence); >>
1020    
1021  Parse a sequence input and convert it into a FASTA string of the desired type. Note  Parse a sequence input and convert it into a FASTA string of the desired type.
 that it is possible to convert a DNA sequence into a protein sequence, but the reverse  
 is not possible.  
1022    
1023  =over 4  =over 4
1024    
 =item incomingType  
   
 C<dna> if this is a DNA sequence, C<prot> if this is a protein sequence.  
   
1025  =item desiredType  =item desiredType
1026    
1027  C<dna> to return a DNA sequence, C<prot> to return a protein sequence. If the  C<dna> to return a DNA sequence, C<prot> to return a protein sequence.
 I<$incomingType> is C<prot> and this value is C<dna>, an error will be thrown.  
1028    
1029  =item sequence  =item sequence
1030    
# Line 983  Line 1046 
1046    
1047  sub ComputeFASTA {  sub ComputeFASTA {
1048      # Get the parameters.      # Get the parameters.
1049      my ($self, $incomingType, $desiredType, $sequence) = @_;      my ($self, $desiredType, $sequence) = @_;
1050      # Declare the return variable. If an error occurs, it will remain undefined.      # Declare the return variable. If an error occurs, it will remain undefined.
1051      my $retVal;      my $retVal;
1052      # This variable will be cleared if an error is detected.      # This variable will be cleared if an error is detected.
1053      my $okFlag = 1;      my $okFlag = 1;
1054      # Create variables to hold the FASTA label and data.      # Create variables to hold the FASTA label and data.
1055      my ($fastaLabel, $fastaData);      my ($fastaLabel, $fastaData);
1056      Trace("FASTA incoming type is $incomingType, desired type is $desiredType.") if T(4);      Trace("FASTA desired type is $desiredType.") if T(4);
1057      # Check for a feature specification.      # Check for a feature specification. The smoking gun for that is a vertical bar.
1058      if ($sequence =~ /^\s*(\w+\|\S+)\s*$/) {      if ($sequence =~ /^\s*(\w+\|\S+)\s*$/) {
1059          # Here we have a feature ID in $1. We'll need the Sprout object to process          # Here we have a feature ID in $1. We'll need the Sprout object to process
1060          # it.          # it.
# Line 1003  Line 1066 
1066          # exist.          # exist.
1067          my ($figID) = $sprout->FeaturesByAlias($fid);          my ($figID) = $sprout->FeaturesByAlias($fid);
1068          if (! $figID) {          if (! $figID) {
1069              $self->SetMessage("No feature found with the ID \"$fid\".");              $self->SetMessage("No gene found with the ID \"$fid\".");
1070              $okFlag = 0;              $okFlag = 0;
1071          } else {          } else {
1072              # Set the FASTA label.              # Set the FASTA label. The ID is the first favored alias.
1073              my $fastaLabel = $fid;              my $favored = $self->Q()->param('FavoredAlias') || 'fig';
1074                my $favorLen = length $favored;
1075                ($fastaLabel) = grep { substr($_, 0, $favorLen) eq $favored } $sprout->FeatureAliases($fid);
1076                if (! $fastaLabel) {
1077                    # In an emergency, fall back to the original ID.
1078                    $fastaLabel = $fid;
1079                }
1080              # Now proceed according to the sequence type.              # Now proceed according to the sequence type.
1081              if ($desiredType eq 'prot') {              if ($desiredType eq 'prot') {
1082                  # We want protein, so get the translation.                  # We want protein, so get the translation.
# Line 1020  Line 1089 
1089                  Trace(length $fastaData . " characters returned for DNA of $fastaLabel.") if T(3);                  Trace(length $fastaData . " characters returned for DNA of $fastaLabel.") if T(3);
1090              }              }
1091          }          }
     } elsif ($incomingType eq 'prot' && $desiredType eq 'dna') {  
         # Here we're being asked to do an impossible conversion.  
         $self->SetMessage("Cannot convert a protein sequence to DNA.");  
         $okFlag = 0;  
1092      } else {      } else {
1093          Trace("Analyzing FASTA sequence.") if T(4);          Trace("Analyzing FASTA sequence.") if T(4);
1094          # Here we are expecting a FASTA. We need to see if there's a label.          # Here we are expecting a FASTA. We need to see if there's a label.
# Line 1036  Line 1101 
1101              Trace("No label found in match to sequence:\n$sequence") if T(4);              Trace("No label found in match to sequence:\n$sequence") if T(4);
1102              # Here we have no label, so we create one and use the entire sequence              # Here we have no label, so we create one and use the entire sequence
1103              # as data.              # as data.
1104              $fastaLabel = "User-specified $incomingType sequence";              $fastaLabel = "User-specified $desiredType sequence";
1105              $fastaData = $sequence;              $fastaData = $sequence;
1106          }          }
1107          # The next step is to clean the junk out of the sequence.          # The next step is to clean the junk out of the sequence.
1108          $fastaData =~ s/\n//g;          $fastaData =~ s/\n//g;
1109          $fastaData =~ s/\s+//g;          $fastaData =~ s/\s+//g;
1110          # Finally, if the user wants to convert to protein, we do it here. Note that          # Finally, verify that it's DNA if we're doing DNA stuff.
1111          # we've already prevented a conversion from protein to DNA.          if ($desiredType eq 'dna' && $fastaData =~ /[^agctxn]/i) {
1112          if ($incomingType ne $desiredType) {              $self->SetMessage("Invalid characters detected. Is the input really a DNA sequence?");
             $fastaData = Sprout::Protein($fastaData);  
             # Check for bad characters.  
             if ($fastaData =~ /X/) {  
                 $self->SetMessage("Invalid characters detected. Is the input really of type $incomingType?");  
                 $okFlag = 0;  
             }  
         } elsif ($desiredType eq 'dna' && $fastaData =~ /[^agct]/i) {  
             $self->SetMessage("Invaid characters detected. Is the input really a DNA sequence?");  
1113              $okFlag = 0;              $okFlag = 0;
1114          }          }
1115      }      }
# Line 1071  Line 1128 
1128      return $retVal;      return $retVal;
1129  }  }
1130    
1131    =head3 SubsystemTree
1132    
1133    C<< my $tree = SearchHelper::SubsystemTree($sprout, %options); >>
1134    
1135    This method creates a subsystem selection tree suitable for passing to
1136    L</SelectionTree>. Each leaf node in the tree will have a link to the
1137    subsystem display page. In addition, each node can have a radio button. The
1138    radio button alue is either C<classification=>I<string>, where I<string> is
1139    a classification string, or C<id=>I<string>, where I<string> is a subsystem ID.
1140    Thus, it can either be used to filter by a group of related subsystems or a
1141    single subsystem.
1142    
1143    =over 4
1144    
1145    =item sprout
1146    
1147    Sprout database object used to get the list of subsystems.
1148    
1149    =item options
1150    
1151    Hash containing options for building the tree.
1152    
1153    =item RETURN
1154    
1155    Returns a reference to a tree list suitable for passing to L</SelectionTree>.
1156    
1157    =back
1158    
1159    The supported options are as follows.
1160    
1161    =over 4
1162    
1163    =item radio
1164    
1165    TRUE if the tree should be configured for radio buttons. The default is FALSE.
1166    
1167    =item links
1168    
1169    TRUE if the tree should be configured for links. The default is TRUE.
1170    
1171    =back
1172    
1173    =cut
1174    
1175    sub SubsystemTree {
1176        # Get the parameters.
1177        my ($sprout, %options) = @_;
1178        # Process the options.
1179        my $optionThing = Tracer::GetOptions({ radio => 0, links => 1 }, \%options);
1180        # Read in the subsystems.
1181        my @subs = $sprout->GetAll(['Subsystem'], "ORDER BY Subsystem(classification), Subsystem(id)", [],
1182                                   ['Subsystem(classification)', 'Subsystem(id)']);
1183        # Put any unclassified subsystems at the end. They will always be at the beginning, so if one
1184        # is at the end, ALL subsystems are unclassified and we don't bother.
1185        if ($#subs >= 0 && $subs[$#subs]->[0] ne '') {
1186            while ($subs[0]->[0] eq '') {
1187                my $classLess = shift @subs;
1188                push @subs, $classLess;
1189            }
1190        }
1191        # Declare the return variable.
1192        my @retVal = ();
1193        # Each element in @subs represents a leaf node, so as we loop through it we will be
1194        # producing one leaf node at a time. The leaf node is represented as a 2-tuple. The
1195        # first element is a semi-colon-delimited list of the classifications for the
1196        # subsystem. There will be a stack of currently-active classifications, which we will
1197        # compare to the incoming classifications from the end backward. A new classification
1198        # requires starting a new branch. A different classification requires closing an old
1199        # branch and starting a new one. Each classification in the stack will also contain
1200        # that classification's current branch. We'll add a fake classification at the
1201        # beginning that we can use to represent the tree as a whole.
1202        my $rootName = '<root>';
1203        # Create the classification stack. Note the stack is a pair of parallel lists,
1204        # one containing names and the other containing content.
1205        my @stackNames = ($rootName);
1206        my @stackContents = (\@retVal);
1207        # Add a null entry at the end of the subsystem list to force an unrolling.
1208        push @subs, ['', undef];
1209        # Loop through the subsystems.
1210        for my $sub (@subs) {
1211            # Pull out the classification list and the subsystem ID.
1212            my ($classString, $id) = @{$sub};
1213            Trace("Processing class \"$classString\" and subsystem $id.") if T(4);
1214            # Convert the classification string to a list with the root classification in
1215            # the front.
1216            my @classList = ($rootName, split($FIG_Config::splitter, $classString));
1217            # Find the leftmost point at which the class list differs from the stack.
1218            my $matchPoint = 0;
1219            while ($matchPoint <= $#stackNames && $matchPoint <= $#classList &&
1220                   $stackNames[$matchPoint] eq $classList[$matchPoint]) {
1221                $matchPoint++;
1222            }
1223            Trace("Match point is $matchPoint. Stack length is " . scalar(@stackNames) .
1224                  ". Class List length is " . scalar(@classList) . ".") if T(4);
1225            # Unroll the stack to the matchpoint.
1226            while ($#stackNames >= $matchPoint) {
1227                my $popped = pop @stackNames;
1228                pop @stackContents;
1229                Trace("\"$popped\" popped from stack.") if T(4);
1230            }
1231            # Start branches for any new classifications.
1232            while ($#stackNames < $#classList) {
1233                # The branch for a new classification contains its radio button
1234                # data and then a list of children. So, at this point, if radio buttons
1235                # are desired, we put them into the content.
1236                my $newLevel = scalar(@stackNames);
1237                my @newClassContent = ();
1238                if ($optionThing->{radio}) {
1239                    my $newClassString = join($FIG_Config::splitter, @classList[1..$newLevel]);
1240                    push @newClassContent, { value => "classification=$newClassString%" };
1241                }
1242                # The new classification node is appended to its parent's content
1243                # and then pushed onto the stack. First, we need the node name.
1244                my $nodeName = $classList[$newLevel];
1245                # Add the classification to its parent. This makes it part of the
1246                # tree we'll be returning to the user.
1247                push @{$stackContents[$#stackNames]}, $nodeName, \@newClassContent;
1248                # Push the classification onto the stack.
1249                push @stackContents, \@newClassContent;
1250                push @stackNames, $nodeName;
1251                Trace("\"$nodeName\" pushed onto stack.") if T(4);
1252            }
1253            # Now the stack contains all our parent branches. We add the subsystem to
1254            # the branch at the top of the stack, but only if it's NOT the dummy node.
1255            if (defined $id) {
1256                # Compute the node name from the ID.
1257                my $nodeName = $id;
1258                $nodeName =~ s/_/ /g;
1259                # Create the node's leaf hash. This depends on the value of the radio
1260                # and link options.
1261                my $nodeContent = {};
1262                if ($optionThing->{links}) {
1263                    # Compute the link value.
1264                    my $linkable = uri_escape($id);
1265                    $nodeContent->{link} = "../FIG/display_subsys.cgi?ssa_name=$linkable;request=show_ssa;sort=by_phylo;show_clusters=1;SPROUT=1";
1266                }
1267                if ($optionThing->{radio}) {
1268                    # Compute the radio value.
1269                    $nodeContent->{value} = "id=$id";
1270                }
1271                # Push the node into its parent branch.
1272                Trace("\"$nodeName\" added to node list.") if T(4);
1273                push @{$stackContents[$#stackNames]}, $nodeName, $nodeContent;
1274            }
1275        }
1276        # Return the result.
1277        return \@retVal;
1278    }
1279    
1280    
1281  =head3 NmpdrGenomeMenu  =head3 NmpdrGenomeMenu
1282    
1283  C<< my $htmlText = $shelp->NmpdrGenomeMenu($menuName, $multiple, \@selected, $rows); >>  C<< my $htmlText = $shelp->NmpdrGenomeMenu($menuName, $multiple, \@selected, $rows); >>
# Line 1220  Line 1427 
1427      push @lines, "</SELECT>";      push @lines, "</SELECT>";
1428      # Check for multiple selection.      # Check for multiple selection.
1429      if ($multiple) {      if ($multiple) {
1430          # Since multi-select is on, we set up some buttons to set and clear selections.          # Multi-select is on, so we need to add some selection helpers. First is
1431            # the search box. This allows the user to type text and have all genomes containing
1432            # the text selected automatically.
1433            my $searchThingName = "${menuName}_SearchThing";
1434            push @lines, "<br />" .
1435                         "<INPUT type=\"button\" name=\"Search\" class=\"button\" value=\"Select genomes containing\" onClick=\"selectViaSearch($menuName, $searchThingName); $showSelect\" />&nbsp;" .
1436                         "<INPUT type=\"text\" name=\"$searchThingName\" size=\"30\" />";
1437            # Next are the buttons to set and clear selections.
1438          push @lines, "<br />";          push @lines, "<br />";
         push @lines, "<INPUT type=\"button\" name=\"SelectAll\" class=\"bigButton\" value=\"Select All\" onClick=\"selectAll($menuName); $showSelect\" />";  
1439          push @lines, "<INPUT type=\"button\" name=\"ClearAll\" class=\"bigButton\"  value=\"Clear All\" onClick=\"clearAll($menuName); $showSelect\" />";          push @lines, "<INPUT type=\"button\" name=\"ClearAll\" class=\"bigButton\"  value=\"Clear All\" onClick=\"clearAll($menuName); $showSelect\" />";
1440            push @lines, "<INPUT type=\"button\" name=\"SelectAll\" class=\"bigButton\" value=\"Select All\" onClick=\"selectAll($menuName); $showSelect\" />";
1441          push @lines, "<INPUT type=\"button\" name=\"NMPDROnly\" class=\"bigButton\"  value=\"Select NMPDR\" onClick=\"selectSome($menuName, $nmpdrCount, true); $showSelect\" />";          push @lines, "<INPUT type=\"button\" name=\"NMPDROnly\" class=\"bigButton\"  value=\"Select NMPDR\" onClick=\"selectSome($menuName, $nmpdrCount, true); $showSelect\" />";
1442          push @lines, "<INPUT type=\"button\" name=\"OtherOnly\" class=\"bigButton\" value=\"Select Supporting\" onClick=\"selectSome($menuName, $nmpdrCount, false); $showSelect\" />";          push @lines, "<INPUT type=\"button\" name=\"OtherOnly\" class=\"bigButton\" value=\"Select Supporting\" onClick=\"selectSome($menuName, $nmpdrCount, false); $showSelect\" />";
         # Now add the search box. This allows the user to type text and have all genomes containing  
         # the text selected automatically.  
         my $searchThingName = "${menuName}_SearchThing";  
         push @lines, "<br>Select genomes containing <INPUT type=\"text\" name=\"$searchThingName\" size=\"30\" />&nbsp;" .  
                      "<INPUT type=\"button\" name=\"Select\" class=\"button\" value=\"Search\" onClick=\"selectViaSearch($menuName, $searchThingName); $showSelect\" />";  
1443          # Add the status display, too.          # Add the status display, too.
1444          push @lines, "<DIV id=\"$divID\" class=\"selectStatus\"></DIV>";          push @lines, "<DIV id=\"$divID\" class=\"selectStatus\"></DIV>";
1445          # Queue to update the status display when the form loads. We need to modify the show statement          # Queue to update the status display when the form loads. We need to modify the show statement
# Line 1317  Line 1526 
1526  =item rows  =item rows
1527    
1528  Reference to a list of table rows. Each table row must be in HTML form with all  Reference to a list of table rows. Each table row must be in HTML form with all
1529  the TR and TD tags set up. The first TD or TH tag in each row will be modified to  the TR and TD tags set up. The first TD or TH tag in the first non-colspanned row
1530  set the width. Everything else will be left as is.  will be modified to set the width. Everything else will be left as is.
1531    
1532  =item RETURN  =item RETURN
1533    
# Line 1333  Line 1542 
1542      my ($self, $rows) = @_;      my ($self, $rows) = @_;
1543      # Get the CGI object.      # Get the CGI object.
1544      my $cgi = $self->Q();      my $cgi = $self->Q();
1545      # Fix the widths on the first column. Note that we eschew the use of the "g"      # The first column of the first row must have its width fixed.
1546        # This flag will be set to FALSE when that happens.
1547        my $needWidth = 1;
1548      # modifier becase we only want to change the first tag. Also, if a width      # modifier becase we only want to change the first tag. Also, if a width
1549      # is already specified on the first column bad things will happen.      # is already specified on the first column bad things will happen.
1550      for my $row (@{$rows}) {      for my $row (@{$rows}) {
1551          $row =~ s/(<td|th)/$1 width="150"/i;          # See if this row needs a width.
1552            if ($needWidth && $row =~ /<(td|th) ([^>]+)>/i) {
1553                # Here we have a first cell and its tag parameters are in $2.
1554                my $elements = $2;
1555                if ($elements !~ /colspan/i) {
1556                    Trace("No colspan tag found in element \'$elements\'.") if T(3);
1557                    # Here there's no colspan, so we plug in the width. We
1558                    # eschew the "g" modifier on the substitution because we
1559                    # only want to update the first cell.
1560                    $row =~ s/(<(td|th))/$1 width="150"/i;
1561                    # Denote we don't need this any more.
1562                    $needWidth = 0;
1563                }
1564            }
1565      }      }
1566      # Create the table.      # Create the table.
1567      my $retVal = $cgi->table({border => 2, cellspacing => 2,      my $retVal = $cgi->table({border => 2, cellspacing => 2,
# Line 1349  Line 1573 
1573    
1574  =head3 SubmitRow  =head3 SubmitRow
1575    
1576  C<< my $htmlText = $shelp->SubmitRow(); >>  C<< my $htmlText = $shelp->SubmitRow($caption); >>
1577    
1578  Returns the HTML text for the row containing the page size control  Returns the HTML text for the row containing the page size control
1579  and the submit button. All searches should have this row somewhere  and the submit button. All searches should have this row somewhere
1580  near the top of the form.  near the top of the form.
1581    
1582    =over 4
1583    
1584    =item caption (optional)
1585    
1586    Caption to be put on the search button. The default is C<Go>.
1587    
1588    =item RETURN
1589    
1590    Returns a table row containing the controls for submitting the search
1591    and tuning the results.
1592    
1593    =back
1594    
1595  =cut  =cut
1596    
1597  sub SubmitRow {  sub SubmitRow {
1598      # Get the parameters.      # Get the parameters.
1599      my ($self) = @_;      my ($self, $caption) = @_;
1600      my $cgi = $self->Q();      my $cgi = $self->Q();
1601        # Compute the button caption.
1602        my $realCaption = (defined $caption ? $caption : 'Go');
1603      # Get the current page size.      # Get the current page size.
1604      my $pageSize = $cgi->param('PageSize');      my $pageSize = $cgi->param('PageSize');
1605      # Get the incoming external-link flag.      # Get the incoming external-link flag.
# Line 1369  Line 1608 
1608      my $retVal = $cgi->Tr($cgi->td("Results/Page"),      my $retVal = $cgi->Tr($cgi->td("Results/Page"),
1609                            $cgi->td($cgi->popup_menu(-name => 'PageSize',                            $cgi->td($cgi->popup_menu(-name => 'PageSize',
1610                                                      -values => [10, 25, 50, 100, 1000],                                                      -values => [10, 25, 50, 100, 1000],
1611                                                      -default => $pageSize) . " " .                                                      -default => $pageSize)),
                                    $cgi->checkbox(-name => 'ShowURL',  
                                                   -value => 1,  
                                                   -label => 'Show URL')),  
1612                            $cgi->td($cgi->submit(-class => 'goButton',                            $cgi->td($cgi->submit(-class => 'goButton',
1613                                                  -name => 'Search',                                                  -name => 'Search',
1614                                                  -value => 'Go')));                                                  -value => $realCaption)));
1615      # Return the result.      # Return the result.
1616      return $retVal;      return $retVal;
1617  }  }
1618    
1619  =head3 FeatureFilterRows  =head3 FeatureFilterRows
1620    
1621  C<< my $htmlText = $shelp->FeatureFilterRows(); >>  C<< my $htmlText = $shelp->FeatureFilterRows(@subset); >>
1622    
1623  This method creates table rows that can be used to filter features. The form  This method creates table rows that can be used to filter features. The form
1624  values can be used to select features by genome using the B<FeatureQuery>  values can be used to select features by genome using the B<FeatureQuery>
1625  object.  object.
1626    
1627    =over 4
1628    
1629    =item subset
1630    
1631    List of rows to display. The default (C<all>) is to display all rows.
1632    C<words> displays the word search box, C<subsys> displays the subsystem
1633    selector, and C<options> displays the options row.
1634    
1635    =item RETURN
1636    
1637    Returns the html text for table rows containing the desired feature filtering controls.
1638    
1639    =back
1640    
1641  =cut  =cut
1642    
1643  sub FeatureFilterRows {  sub FeatureFilterRows {
1644      # Get the parameters.      # Get the parameters.
1645      my ($self) = @_;      my ($self, @subset) = @_;
1646        if (@subset == 0 || $subset[0] eq 'all') {
1647            @subset = qw(words subsys options);
1648        }
1649      # Return the result.      # Return the result.
1650      return FeatureQuery::FilterRows($self);      return FeatureQuery::FilterRows($self, @subset);
1651  }  }
1652    
1653  =head3 GBrowseFeatureURL  =head3 GBrowseFeatureURL
# Line 1469  Line 1722 
1722          $seg_id =~ s/:/--/g;          $seg_id =~ s/:/--/g;
1723          Trace("Show limits are ($show_start,$show_stop) in genome $genomeID with ref $seg_id.") if T(3);          Trace("Show limits are ($show_start,$show_stop) in genome $genomeID with ref $seg_id.") if T(3);
1724          # Assemble all the pieces.          # Assemble all the pieces.
1725          $retVal = "gbrowse.cgi/GB_$genomeID?ref=$seg_id&start=$show_start&stop=$show_stop";          $retVal = "gbrowse.cgi/GB_$genomeID?ref=$seg_id;start=$show_start;stop=$show_stop";
1726      }      }
1727      # Return the result.      # Return the result.
1728      return $retVal;      return $retVal;
# Line 1562  Line 1815 
1815    
1816  =head3 ComputeSearchURL  =head3 ComputeSearchURL
1817    
1818  C<< my $url = $shelp->ComputeSearchURL(); >>  C<< my $url = $shelp->ComputeSearchURL(%overrides); >>
1819    
1820  Compute the GET-style URL for the current search. In order for this to work, there  Compute the GET-style URL for the current search. In order for this to work, there
1821  must be a copy of the search form on the current page. This will always be the  must be a copy of the search form on the current page. This will always be the
# Line 1572  Line 1825 
1825  main complication is that if the user specified all genomes, we'll want to  main complication is that if the user specified all genomes, we'll want to
1826  remove the parameter entirely from a get-style URL.  remove the parameter entirely from a get-style URL.
1827    
1828    =over 4
1829    
1830    =item overrides
1831    
1832    Hash containing override values for the parameters, where the parameter name is
1833    the key and the parameter value is the override value. If the override value is
1834    C<undef>, the parameter will be deleted from the result.
1835    
1836    =item RETURN
1837    
1838    Returns a GET-style URL for invoking the search with the specified overrides.
1839    
1840    =back
1841    
1842  =cut  =cut
1843    
1844  sub ComputeSearchURL {  sub ComputeSearchURL {
1845      # Get the parameters.      # Get the parameters.
1846      my ($self) = @_;      my ($self, %overrides) = @_;
1847      # Get the database and CGI query object.      # Get the database and CGI query object.
1848      my $cgi = $self->Q();      my $cgi = $self->Q();
1849      my $sprout = $self->DB();      my $sprout = $self->DB();
# Line 1603  Line 1870 
1870          # a singleton list, but that's okay.          # a singleton list, but that's okay.
1871          my @values = split (/\0/, $parms{$parmKey});          my @values = split (/\0/, $parms{$parmKey});
1872          # Check for special cases.          # Check for special cases.
1873          if (grep { $_ eq $parmKey } qw(SessionID ResultCount Page PageSize Trace TF ShowURL)) {          if (grep { $_ eq $parmKey } qw(SessionID ResultCount Page PageSize Trace TF)) {
1874              # These are bookkeeping parameters we don't need to start a search.              # These are bookkeeping parameters we don't need to start a search.
1875              @values = ();              @values = ();
1876          } elsif ($parmKey =~ /_SearchThing$/) {          } elsif ($parmKey =~ /_SearchThing$/) {
# Line 1617  Line 1884 
1884              if ($allFlag) {              if ($allFlag) {
1885                  @values = ();                  @values = ();
1886              }              }
1887            } elsif (exists $overrides{$parmKey}) {
1888                # Here the value is being overridden, so we skip it for now.
1889                @values = ();
1890          }          }
1891          # If we still have values, create the URL parameters.          # If we still have values, create the URL parameters.
1892          if (@values) {          if (@values) {
1893              push @urlList, map { "$parmKey=" . uri_escape($_) } @values;              push @urlList, map { "$parmKey=" . uri_escape($_) } @values;
1894          }          }
1895      }      }
1896        # Now do the overrides.
1897        for my $overKey (keys %overrides) {
1898            # Only use this override if it's not a delete marker.
1899            if (defined $overrides{$overKey}) {
1900                push @urlList, "$overKey=" . uri_escape($overrides{$overKey});
1901            }
1902        }
1903      # Add the parameters to the URL.      # Add the parameters to the URL.
1904      $retVal .= "?" . join(";", @urlList);      $retVal .= "?" . join(";", @urlList);
1905      # Return the result.      # Return the result.
# Line 1672  Line 1949 
1949  Return a list of advanced class names. This list is used to generate the directory  Return a list of advanced class names. This list is used to generate the directory
1950  of available searches on the search page.  of available searches on the search page.
1951    
1952  The reason we have to convert the list from a string is that the B<NMPDRSetup.pl>  We use the %INC variable to accomplish this.
 script is only able to insert strings into the generated B<FIG_Config> file.  
1953    
1954  =cut  =cut
1955    
1956  sub AdvancedClassList {  sub AdvancedClassList {
1957      return split /\s+/, $FIG_Config::advanced_classes;      my @retVal = map { $_ =~ /^SH(\w+)\.pm/; $1 } grep { $_ =~ /^SH/ } keys %INC;
1958        return @retVal;
1959    }
1960    
1961    =head3 SelectionTree
1962    
1963    C<< my $htmlText = SearchHelper::SelectionTree($cgi, \%tree, %options); >>
1964    
1965    Display a selection tree.
1966    
1967    This method creates the HTML for a tree selection control. The tree is implemented as a set of
1968    nested HTML unordered lists. Each selectable element of the tree will contain a radio button. In
1969    addition, some of the tree nodes can contain hyperlinks.
1970    
1971    The tree itself is passed in as a multi-level list containing node names followed by
1972    contents. Each content element is a reference to a similar list. The first element of
1973    each list may be a hash reference. If so, it should contain one or both of the following
1974    keys.
1975    
1976    =over 4
1977    
1978    =item link
1979    
1980    The navigation URL to be popped up if the user clicks on the node name.
1981    
1982    =item value
1983    
1984    The form value to be returned if the user selects the tree node.
1985    
1986    =back
1987    
1988    The presence of a C<link> key indicates the node name will be hyperlinked. The presence of
1989    a C<value> key indicates the node name will have a radio button. If a node has no children,
1990    you may pass it a hash reference instead of a list reference.
1991    
1992    The following example shows the hash for a three-level tree with links on the second level and
1993    radio buttons on the third.
1994    
1995        [   Objects => [
1996                Entities => [
1997                    {link => "../docs/WhatIsAnEntity.html"},
1998                    Genome => {value => 'GenomeData'},
1999                    Feature => {value => 'FeatureData'},
2000                    Contig => {value => 'ContigData'},
2001                ],
2002                Relationships => [
2003                    {link => "../docs/WhatIsARelationShip.html"},
2004                    HasFeature => {value => 'GenomeToFeature'},
2005                    IsOnContig => {value => 'FeatureToContig'},
2006                ]
2007            ]
2008        ]
2009    
2010    Note how each leaf of the tree has a hash reference for its value, while the branch nodes
2011    all have list references.
2012    
2013    This next example shows how to set up a taxonomy selection field. The value returned
2014    by the tree control will be the taxonomy string for the selected node ready for use
2015    in a LIKE-style SQL filter. Only the single branch ending in campylobacter is shown for
2016    reasons of space.
2017    
2018        [   All => [
2019                {value => "%"},
2020                Bacteria => [
2021                    {value => "Bacteria%"},
2022                    Proteobacteria => [
2023                        {value => "Bacteria; Proteobacteria%"},
2024                        Epsilonproteobacteria => [
2025                            {value => "Bacteria; Proteobacteria;Epsilonproteobacteria%"},
2026                            Campylobacterales => [
2027                                {value => "Bacteria; Proteobacteria; Epsilonproteobacteria; Campylobacterales%"},
2028                                Campylobacteraceae =>
2029                                    {value => "Bacteria; Proteobacteria; Epsilonproteobacteria; Campylobacterales; Campylobacteraceae%"},
2030                                ...
2031                            ]
2032                            ...
2033                        ]
2034                        ...
2035                    ]
2036                    ...
2037                ]
2038                ...
2039            ]
2040        ]
2041    
2042    
2043    This method of tree storage allows the caller to control the order in which the tree nodes
2044    are displayed and to completely control value selection and use of hyperlinks. It is, however
2045    a bit complicated. Eventually, tree-building classes will be provided to simplify things.
2046    
2047    The parameters to this method are as follows.
2048    
2049    =over 4
2050    
2051    =item cgi
2052    
2053    CGI object used to generate the HTML.
2054    
2055    =item tree
2056    
2057    Reference to a hash describing a tree. See the description above.
2058    
2059    =item options
2060    
2061    Hash containing options for the tree display.
2062    
2063    =back
2064    
2065    The allowable options are as follows
2066    
2067    =over 4
2068    
2069    =item nodeImageClosed
2070    
2071    URL of the image to display next to the tree nodes when they are collapsed. Clicking
2072    on the image will expand a section of the tree. The default is C<../FIG/Html/plus.gif>.
2073    
2074    =item nodeImageOpen
2075    
2076    URL of the image to display next to the tree nodes when they are expanded. Clicking
2077    on the image will collapse a section of the tree. The default is C<../FIG/Html/minus.gif>.
2078    
2079    =item style
2080    
2081    Style to use for the tree. The default is C<tree>. Because the tree style is implemented
2082    as nested lists, the key components of this style are the definitions for the C<ul> and
2083    C<li> tags. The default style file contains the following definitions.
2084    
2085        .tree ul {
2086           margin-left: 0; padding-left: 22px
2087        }
2088        .tree li {
2089            list-style-type: none;
2090        }
2091    
2092    The default image is 22 pixels wide, so in the above scheme each tree level is indented from its
2093    parent by the width of the node image. This use of styles limits the things we can do in formatting
2094    the tree, but it has the advantage of vastly simplifying the tree creation.
2095    
2096    =item name
2097    
2098    Field name to give to the radio buttons in the tree. The default is C<selection>.
2099    
2100    =item target
2101    
2102    Frame target for links. The default is C<_self>.
2103    
2104    =item selected
2105    
2106    If specified, the value of the radio button to be pre-selected.
2107    
2108    =back
2109    
2110    =cut
2111    
2112    sub SelectionTree {
2113        # Get the parameters.
2114        my ($cgi, $tree, %options) = @_;
2115        # Get the options.
2116        my $optionThing = Tracer::GetOptions({ name => 'selection',
2117                                               nodeImageClosed => '../FIG/Html/plus.gif',
2118                                               nodeImageOpen => '../FIG/Html/minus.gif',
2119                                               style => 'tree',
2120                                               target => '_self',
2121                                               selected => undef},
2122                                             \%options);
2123        # Declare the return variable. We'll do the standard thing with creating a list
2124        # of HTML lines and rolling them together at the end.
2125        my @retVal = ();
2126        # Only proceed if the tree is present.
2127        if (defined($tree)) {
2128            # Validate the tree.
2129            if (ref $tree ne 'ARRAY') {
2130                Confess("Selection tree is not a list reference.");
2131            } elsif (scalar @{$tree} == 0) {
2132                # The tree is empty, so we do nothing.
2133            } elsif ($tree->[0] eq 'HASH') {
2134                Confess("Hash reference found at start of selection tree. The tree as a whole cannot have attributes, only tree nodes.");
2135            } else {
2136                # Here we have a real tree. Apply the tree style.
2137                push @retVal, $cgi->start_div({ class => $optionThing->{style} });
2138                # Give us a DIV ID.
2139                my $divID = GetDivID($optionThing->{name});
2140                # Show the tree.
2141                push @retVal, ShowBranch($cgi, "(root)", $divID, $tree, $optionThing, 'block');
2142                # Close the DIV block.
2143                push @retVal, $cgi->end_div();
2144            }
2145        }
2146        # Return the result.
2147        return join("\n", @retVal, "");
2148    }
2149    
2150    =head3 ShowBranch
2151    
2152    C<< my @htmlLines = SearchHelper::ShowBranch($cgi, $label, $id, $branch, $options, $displayType); >>
2153    
2154    This is a recursive method that displays a branch of the tree.
2155    
2156    =over 4
2157    
2158    =item cgi
2159    
2160    CGI object used to format HTML.
2161    
2162    =item label
2163    
2164    Label of this tree branch. It is only used in error messages.
2165    
2166    =item id
2167    
2168    ID to be given to this tree branch. The ID is used in the code that expands and collapses
2169    tree nodes.
2170    
2171    =item branch
2172    
2173    Reference to a list containing the content of the tree branch. The list contains an optional
2174    hash reference that is ignored and the list of children, each child represented by a name
2175    and then its contents. The contents could by a hash reference (indicating the attributes
2176    of a leaf node), or another tree branch.
2177    
2178    =item options
2179    
2180    Options from the original call to L</SelectionTree>.
2181    
2182    =item displayType
2183    
2184    C<block> if the contents of this list are to be displayed, C<none> if they are to be
2185    hidden.
2186    
2187    =item RETURN
2188    
2189    Returns one or more HTML lines that can be used to display the tree branch.
2190    
2191    =back
2192    
2193    =cut
2194    
2195    sub ShowBranch {
2196        # Get the parameters.
2197        my ($cgi, $label, $id, $branch, $options, $displayType) = @_;
2198        # Declare the return variable.
2199        my @retVal = ();
2200        # Start the branch.
2201        push @retVal, $cgi->start_ul({ id => $id, style => "display:$displayType" });
2202        # Check for the hash and choose the start location accordingly.
2203        my $i0 = (ref $branch->[0] eq 'HASH' ? 1 : 0);
2204        # Get the list length.
2205        my $i1 = scalar(@{$branch});
2206        # Verify we have an even number of elements.
2207        if (($i1 - $i0) % 2 != 0) {
2208            Trace("Branch elements are from $i0 to $i1.") if T(3);
2209            Confess("Odd number of elements in tree branch $label.");
2210        } else {
2211            # Loop through the elements.
2212            for (my $i = $i0; $i < $i1; $i += 2) {
2213                # Get this node's label and contents.
2214                my ($myLabel, $myContent) = ($branch->[$i], $branch->[$i+1]);
2215                # Get an ID for this node's children (if any).
2216                my $myID = GetDivID($options->{name});
2217                # Now we need to find the list of children and the options hash.
2218                # This is a bit ugly because we allow the shortcut of a hash without an
2219                # enclosing list. First, we need some variables.
2220                my $attrHash = {};
2221                my @childHtml = ();
2222                my $hasChildren = 0;
2223                if (! ref $myContent) {
2224                    Confess("Invalid tree definition. Scalar found as content of node \"$myLabel\".");
2225                } elsif (ref $myContent eq 'HASH') {
2226                    # Here the node is a leaf and its content contains the link/value hash.
2227                    $attrHash = $myContent;
2228                } elsif (ref $myContent eq 'ARRAY') {
2229                    # Here the node may be a branch. Its content is a list.
2230                    my $len = scalar @{$myContent};
2231                    if ($len >= 1) {
2232                        # Here the first element of the list could by the link/value hash.
2233                        if (ref $myContent->[0] eq 'HASH') {
2234                            $attrHash = $myContent->[0];
2235                            # If there's data in the list besides the hash, it's our child list.
2236                            # We can pass the entire thing as the child list, because the hash
2237                            # is ignored.
2238                            if ($len > 1) {
2239                                $hasChildren = 1;
2240                            }
2241                        } else {
2242                            $hasChildren = 1;
2243                        }
2244                        # If we have children, create the child list with a recursive call.
2245                        if ($hasChildren) {
2246                            Trace("Processing children of $myLabel.") if T(4);
2247                            push @childHtml, ShowBranch($cgi, $myLabel, $myID, $myContent, $options, 'none');
2248                            Trace("Children of $myLabel finished.") if T(4);
2249                        }
2250                    }
2251                }
2252                # Okay, it's time to pause and take stock. We have the label of the current node
2253                # in $myLabel, its attributes in $attrHash, and if it is NOT a leaf node, we
2254                # have a child list in @childHtml. If it IS a leaf node, $hasChildren is 0.
2255                # Compute the image HTML. It's tricky, because we have to deal with the open and
2256                # closed images.
2257                my @images = ($options->{nodeImageOpen}, $options->{nodeImageClosed});
2258                my $image = $images[$hasChildren];
2259                my $prefixHtml = $cgi->img({src => $image, id => "${myID}img"});
2260                if ($hasChildren) {
2261                    # If there are children, we wrap the image in a toggle hyperlink.
2262                    $prefixHtml = $cgi->a({ onClick => "javascript:treeToggle('$myID','$images[0]', '$images[1]')" },
2263                                          $prefixHtml);
2264                }
2265                # Now the radio button, if any. Note we use "defined" in case the user wants the
2266                # value to be 0.
2267                if (defined $attrHash->{value}) {
2268                    # Due to a glitchiness in the CGI stuff, we have to build the attribute
2269                    # hash for the "input" method. If the item is pre-selected, we add
2270                    # "checked => undef" to the hash. Otherwise, we can't have "checked"
2271                    # at all.
2272                    my $radioParms = { type => 'radio',
2273                                       name => $options->{name},
2274                                       value => $attrHash->{value},
2275                                     };
2276                    if (defined $options->{selected} && $options->{selected} eq $attrHash->{value}) {
2277                        $radioParms->{checked} = undef;
2278                    }
2279                    $prefixHtml .= $cgi->input($radioParms);
2280                }
2281                # Next, we format the label.
2282                my $labelHtml = $myLabel;
2283                Trace("Formatting tree node for \"$myLabel\".") if T(4);
2284                # Apply a hyperlink if necessary.
2285                if (defined $attrHash->{link}) {
2286                    $labelHtml = $cgi->a({ href => $attrHash->{link}, target => $options->{target} },
2287                                         $labelHtml);
2288                }
2289                # Finally, roll up the child HTML. If there are no children, we'll get a null string
2290                # here.
2291                my $childHtml = join("\n", @childHtml);
2292                # Now we have all the pieces, so we can put them together.
2293                push @retVal, $cgi->li("$prefixHtml$labelHtml$childHtml");
2294            }
2295        }
2296        # Close the tree branch.
2297        push @retVal, $cgi->end_ul();
2298        # Return the result.
2299        return @retVal;
2300    }
2301    
2302    =head3 GetDivID
2303    
2304    C<< my $idString = SearchHelper::GetDivID($name); >>
2305    
2306    Return a new HTML ID string.
2307    
2308    =over 4
2309    
2310    =item name
2311    
2312    Name to be prefixed to the ID string.
2313    
2314    =item RETURN
2315    
2316    Returns a hopefully-unique ID string.
2317    
2318    =back
2319    
2320    =cut
2321    
2322    sub GetDivID {
2323        # Get the parameters.
2324        my ($name) = @_;
2325        # Compute the ID.
2326        my $retVal = "elt_$name$divCount";
2327        # Increment the counter to make sure this ID is not re-used.
2328        $divCount++;
2329        # Return the result.
2330        return $retVal;
2331  }  }
2332    
2333  =head2 Feature Column Methods  =head2 Feature Column Methods
2334    
2335  The methods in this column manage feature column data. If you want to provide the  The methods in this section manage feature column data. If you want to provide the
2336  capability to include new types of data in feature columns, then all the changes  capability to include new types of data in feature columns, then all the changes
2337  are made to this section of the source file. Technically, this should be implemented  are made to this section of the source file. Technically, this should be implemented
2338  using object-oriented methods, but this is simpler for non-programmers to maintain.  using object-oriented methods, but this is simpler for non-programmers to maintain.
# Line 1691  Line 2340 
2340  the name for the protein page link column is C<protlink>. If the column is to appear  the name for the protein page link column is C<protlink>. If the column is to appear
2341  in the default list of feature columns, add it to the list returned by  in the default list of feature columns, add it to the list returned by
2342  L</DefaultFeatureColumns>. Then add code to produce the column title to  L</DefaultFeatureColumns>. Then add code to produce the column title to
2343  L</FeatureColumnTitle> and code to produce its value to L</FeatureColumnValue>, and  L</FeatureColumnTitle> and code to produce its value to L</FeatureColumnValue>. If the
2344  everything else will happen automatically.  feature column should be excluded from downloads, add it to the C<FeatureColumnSkip>
2345    hash. Everything else will happen automatically.
2346    
2347  There is one special column name syntax for extra columns (that is, nonstandard  There is a special column name syntax for extra columns (that is, nonstandard
2348  feature columns). If the column name begins with C<X=>, then it is presumed to be  feature columns). If the column name begins with C<X=>, then it is presumed to be
2349  an extra column. The column title is the text after the C<X=>, and its value is  an extra column. The column title is the text after the C<X=>, and its value is
2350  pulled from the extra column hash.  pulled from the extra column hash.
2351    
2352    =cut
2353    
2354    # This hash is used to determine which columns should not be included in downloads.
2355    my %FeatureColumnSkip = map { $_ => 1 } qw(gblink viewerlink protlink);
2356    
2357  =head3 DefaultFeatureColumns  =head3 DefaultFeatureColumns
2358    
2359  C<< my @colNames = $shelp->DefaultFeatureColumns(); >>  C<< my @colNames = $shelp->DefaultFeatureColumns(); >>
# Line 1758  Line 2413 
2413      } elsif ($colName =~ /^keyword:(.+)$/) {      } elsif ($colName =~ /^keyword:(.+)$/) {
2414          $retVal = ucfirst $1;          $retVal = ucfirst $1;
2415      } elsif ($colName eq 'orgName') {      } elsif ($colName eq 'orgName') {
2416          $retVal = "Feature Name";          $retVal = "Organism and Gene ID";
2417      } elsif ($colName eq 'protlink') {      } elsif ($colName eq 'protlink') {
2418          $retVal = "NMPDR Protein Page";          $retVal = "NMPDR Protein Page";
2419        } elsif ($colName eq 'viewerlink') {
2420            $retVal = "Annotation Page";
2421      } elsif ($colName eq 'subsystem') {      } elsif ($colName eq 'subsystem') {
2422          $retVal = "Subsystems";          $retVal = "Subsystems";
2423      }      }
# Line 1768  Line 2425 
2425      return $retVal;      return $retVal;
2426  }  }
2427    
2428    =head3 FeatureColumnDownload
2429    
2430    C<< my $keep = $shelp->FeatureColumnDownload($colName); >>
2431    
2432    Return TRUE if the named feature column is to be kept when downloading, else FALSE.
2433    
2434    =over 4
2435    
2436    =item colName
2437    
2438    Name of the relevant feature column.
2439    
2440    =item RETURN
2441    
2442    Return TRUE if the named column should be kept while downloading, else FALSE. In general,
2443    FALSE is returned if the column generates a button, image, or other purely-HTML value.
2444    
2445    =back
2446    
2447    =cut
2448    
2449    sub FeatureColumnDownload {
2450        # Get the parameters.
2451        my ($self, $colName) = @_;
2452        # Return the determination. We download the column if it's not in the skip-hash.
2453        # Note we return 0 and 1 instead of 1 and undef because it simplifies some tracing.
2454        return (exists $FeatureColumnSkip{$colName} ? 0 : 1);
2455    }
2456    
2457    
2458  =head3 FeatureColumnValue  =head3 FeatureColumnValue
2459    
# Line 1783  Line 2469 
2469    
2470  =item record  =item record
2471    
2472  DBObject record for the feature being displayed in the current row.  ERDBObject record for the feature being displayed in the current row.
2473    
2474  =item extraCols  =item extraCols
2475    
# Line 1822  Line 2508 
2508      } elsif ($colName eq 'alias') {      } elsif ($colName eq 'alias') {
2509          # In this case, the user wants a list of external aliases for the feature.          # In this case, the user wants a list of external aliases for the feature.
2510          # These are very expensive, so we compute them when the row is displayed.          # These are very expensive, so we compute them when the row is displayed.
2511          $retVal = "%%alias=$fid";          # To do the computation, we need to know the favored alias type and the
2512            # feature ID.
2513            my $favored = $cgi->param("FavoredAlias") || "fig";
2514            $retVal = "%%alias=$fid,$favored";
2515      } elsif ($colName eq 'fid') {      } elsif ($colName eq 'fid') {
2516          # Here we have the raw feature ID. We hyperlink it to the protein page.          # Here we have the raw feature ID. We hyperlink it to the protein page.
2517          $retVal = HTML::set_prot_links($fid);          $retVal = HTML::set_prot_links($fid);
# Line 1831  Line 2520 
2520          ($retVal) = $record->Value('Feature(assignment)');          ($retVal) = $record->Value('Feature(assignment)');
2521      } elsif ($colName eq 'gblink') {      } elsif ($colName eq 'gblink') {
2522          # Here we want a link to the GBrowse page using the official GBrowse button.          # Here we want a link to the GBrowse page using the official GBrowse button.
2523          my $gurl = "GetGBrowse.cgi?fid=$fid";          $retVal = FakeButton('GBrowse', "GetGBrowse.cgi", undef,
2524          $retVal = $cgi->a({ href => $gurl, title => "GBrowse for $fid" },                            fid => $fid);
                           $cgi->img({ src => "../images/button-gbrowse.png",  
                                       border => 0 })  
                          );  
2525      } elsif ($colName eq 'group') {      } elsif ($colName eq 'group') {
2526          # Get the NMPDR group name.          # Get the NMPDR group name.
2527          my (undef, $group) = $self->OrganismData($fid);          my (undef, $group) = $self->OrganismData($fid);
# Line 1852  Line 2538 
2538          $retVal = $self->FeatureName($fid);          $retVal = $self->FeatureName($fid);
2539      } elsif ($colName eq 'protlink') {      } elsif ($colName eq 'protlink') {
2540          # Here we want a link to the protein page using the official NMPDR button.          # Here we want a link to the protein page using the official NMPDR button.
2541          my $hurl = HTML::fid_link($cgi, $fid, 0, 1);          $retVal = FakeButton('NMPDR', "protein.cgi", undef,
2542          $retVal = $cgi->a({ href => $hurl, title => "Protein page for $fid" },                            prot => $fid, SPROUT => 1, new_framework => 0,
2543                            $cgi->img({ src => "../images/button-nmpdr.png",                            user => '');
2544                                       border => 0 })      } elsif ($colName eq 'viewerlink') {
2545                           );          # Here we want a link to the SEED viewer page using the official viewer button.
2546            $retVal = FakeButton('Annotation', "index.cgi", undef,
2547                                 action => 'ShowAnnotation', prot => $fid);
2548      }elsif ($colName eq 'subsystem') {      }elsif ($colName eq 'subsystem') {
2549          # Another run-time column: subsystem list.          # Another run-time column: subsystem list.
2550          $retVal = "%%subsystem=$fid";          $retVal = "%%subsystem=$fid";
# Line 1902  Line 2590 
2590      # Separate the text into a type and data.      # Separate the text into a type and data.
2591      if ($type eq 'alias') {      if ($type eq 'alias') {
2592          # Here the caller wants external alias links for a feature. The text          # Here the caller wants external alias links for a feature. The text
2593          # is the feature ID.          # parameter for computing the alias is the feature ID followed by
2594          my $fid = $text;          # the favored alias type.
2595          # The complicated part is we have to hyperlink them. First, get the          my ($fid, $favored) = split /\s*,\s*/, $text;
2596          # aliases.          # The complicated part is we have to hyperlink them and handle the
2597            # favorites. First, get the aliases.
2598          Trace("Generating aliases for feature $fid.") if T(4);          Trace("Generating aliases for feature $fid.") if T(4);
2599          my @aliases = $sprout->FeatureAliases($fid);          my @aliases = sort $sprout->FeatureAliases($fid);
2600          # Only proceed if we found some.          # Only proceed if we found some.
2601          if (@aliases) {          if (@aliases) {
2602              # Join the aliases into a comma-delimited list.              # Split the aliases into favored and unfavored.
2603              my $aliasList = join(", ", @aliases);              my @favored = ();
2604                my @unfavored = ();
2605                for my $alias (@aliases) {
2606                    # Use substr instead of pattern match because $favored is specified by the user
2607                    # and we don't want him to put funny meta-characters in there.
2608                    if (substr($alias, 0, length($favored)) eq $favored) {
2609                        push @favored, $alias;
2610                    } else {
2611                        push @unfavored, $alias;
2612                    }
2613                }
2614                # Rejoin the aliases into a comma-delimited list, with the favored ones first.
2615                my $aliasList = join(", ", @favored, @unfavored);
2616              # Ask the HTML processor to hyperlink them.              # Ask the HTML processor to hyperlink them.
2617              $retVal = HTML::set_prot_links($cgi, $aliasList);              $retVal = HTML::set_prot_links($cgi, $aliasList);
2618          }          }
# Line 1923  Line 2624 
2624          # Get the subsystems.          # Get the subsystems.
2625          Trace("Generating subsystems for feature $fid.") if T(4);          Trace("Generating subsystems for feature $fid.") if T(4);
2626          my %subs = $sprout->SubsystemsOf($fid);          my %subs = $sprout->SubsystemsOf($fid);
2627          # Convert them to links.          # Extract the subsystem names.
2628          my @links = map { HTML::sub_link($cgi, $_) } sort keys %subs;          my @names = map { HTML::sub_link($cgi, $_) } sort keys %subs;
2629          # String them into a list.          # String them into a list.
2630          $retVal = join(", ", @links);          $retVal = join(", ", @names);
2631      } elsif ($type =~ /^keyword:(.+)$/) {      } elsif ($type =~ /^keyword:(.+)$/) {
2632          # Here the caller wants the value of the named keyword. The text is the          # Here the caller wants the value of the named keyword. The text is the
2633          # feature ID.          # feature ID.
# Line 2010  Line 2711 
2711      return ($name, $displayGroup);      return ($name, $displayGroup);
2712  }  }
2713    
2714    =head3 ValidateKeywords
2715    
2716    C<< my $okFlag = $shelp->ValidateKeywords($keywordString, $required); >>
2717    
2718    Insure that a keyword string is reasonably valid. If it is invalid, a message will be
2719    set.
2720    
2721    =over 4
2722    
2723    =item keywordString
2724    
2725    Keyword string specified as a parameter to the current search.
2726    
2727    =item required
2728    
2729    TRUE if there must be at least one keyword specified, else FALSE.
2730    
2731    =item RETURN
2732    
2733    Returns TRUE if the keyword string is valid, else FALSE. Note that a null keyword string
2734    is acceptable if the I<$required> parameter is not specified.
2735    
2736    =back
2737    
2738    =cut
2739    
2740    sub ValidateKeywords {
2741        # Get the parameters.
2742        my ($self, $keywordString, $required) = @_;
2743        # Declare the return variable.
2744        my $retVal = 0;
2745        my @wordList = split /\s+/, $keywordString;
2746        # Right now our only real worry is a list of all minus words. The problem with it is that
2747        # it will return an incorrect result.
2748        my @plusWords = grep { $_ =~ /^[^\-]/ } @wordList;
2749        if (! @wordList) {
2750            if ($required) {
2751                $self->SetMessage("No search words specified.");
2752            } else {
2753                $retVal = 1;
2754            }
2755        } elsif (! @plusWords) {
2756            $self->SetMessage("At least one keyword must be positive. All the keywords entered are preceded by minus signs.");
2757        } else {
2758            $retVal = 1;
2759        }
2760        # Return the result.
2761        return $retVal;
2762    }
2763    
2764    =head3 FakeButton
2765    
2766    C<< my $html = SearchHelper::FakeButton($caption, $url, $target, %parms); >>
2767    
2768    Create a fake button that hyperlinks to the specified URL with the specified parameters.
2769    Unlike a real button, this one won't visibly click, but it will take the user to the
2770    correct place.
2771    
2772    The parameters of this method are deliberately identical to L</Formlet> so that we
2773    can switch easily from real buttons to fake ones in the code.
2774    
2775    =over 4
2776    
2777    =item caption
2778    
2779    Caption to be put on the button.
2780    
2781    =item url
2782    
2783    URL for the target page or script.
2784    
2785    =item target
2786    
2787    Frame or target in which the new page should appear. If C<undef> is specified,
2788    the default target will be used.
2789    
2790    =item parms
2791    
2792    Hash containing the parameter names as keys and the parameter values as values.
2793    These will be appended to the URL.
2794    
2795    =back
2796    
2797    =cut
2798    
2799    sub FakeButton {
2800        # Get the parameters.
2801        my ($caption, $url, $target, %parms) = @_;
2802        # Declare the return variable.
2803        my $retVal;
2804        # Compute the target URL.
2805        my $targetUrl = "$url?" . join(";", map { "$_=" . uri_escape($parms{$_}) } keys %parms);
2806        # Compute the target-frame HTML.
2807        my $targetHtml = ($target ? " target=\"$target\"" : "");
2808        # Assemble the result.
2809        return "<a href=\"$targetUrl\" $targetHtml><div class=\"button2 button\">$caption</div></a>";
2810    }
2811    
2812    =head3 Formlet
2813    
2814    C<< my $html = SearchHelper::Formlet($caption, $url, $target, %parms); >>
2815    
2816    Create a mini-form that posts to the specified URL with the specified parameters. The
2817    parameters will be stored in hidden fields, and the form's only visible control will
2818    be a submit button with the specified caption.
2819    
2820    Note that we don't use B<CGI.pm> services here because they generate forms with extra characters
2821    and tags that we don't want to deal with.
2822    
2823    =over 4
2824    
2825    =item caption
2826    
2827    Caption to be put on the form button.
2828    
2829    =item url
2830    
2831    URL to be put in the form's action parameter.
2832    
2833    =item target
2834    
2835    Frame or target in which the form results should appear. If C<undef> is specified,
2836    the default target will be used.
2837    
2838    =item parms
2839    
2840    Hash containing the parameter names as keys and the parameter values as values.
2841    
2842    =back
2843    
2844    =cut
2845    
2846    sub Formlet {
2847        # Get the parameters.
2848        my ($caption, $url, $target, %parms) = @_;
2849        # Compute the target HTML.
2850        my $targetHtml = ($target ? " target=\"$target\"" : "");
2851        # Start the form.
2852        my $retVal = "<form method=\"POST\" action=\"$url\"$target>";
2853        # Add the parameters.
2854        for my $parm (keys %parms) {
2855            $retVal .= "<input type=\"hidden\" name=\"$parm\" value=\"$parms{$parm}\" />";
2856        }
2857        # Put in the button.
2858        $retVal .= "<input type=\"submit\" name=\"submit\" value=\"$caption\" class=\"button\" />";
2859        # Close the form.
2860        $retVal .= "</form>";
2861        # Return the result.
2862        return $retVal;
2863    }
2864    
2865  =head2 Virtual Methods  =head2 Virtual Methods
2866    
2867  =head3 Form  =head3 Form
# Line 2073  Line 2925 
2925      return $retVal;      return $retVal;
2926  }  }
2927    
2928    =head3 PrintLine
2929    
2930    C<< $shelp->PrintLine($message); >>
2931    
2932    Print a line of CGI output. This is used during the operation of the B<Find> method while
2933    searching, so the user sees progress in real-time.
2934    
2935    =over 4
2936    
2937    =item message
2938    
2939    HTML text to display.
2940    
2941    =back
2942    
2943    =cut
2944    
2945    sub PrintLine {
2946        # Get the parameters.
2947        my ($self, $message) = @_;
2948        # Send them to the output.
2949        print "$message\n";
2950    }
2951    
2952    
2953  1;  1;

Legend:
Removed from v.1.14  
changed lines
  Added in v.1.29

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3