# SrcToolBar
# Copyright 2000 Red Hat, Inc.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License (GPL) as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# ----------------------------------------------------------------------
# Implements a toolbar that is attached to a source window.
#
#   PUBLIC ATTRIBUTES:
#
#
#   METHODS:
#
#     configure ....... used to change public attributes
#
#   PRIVATE METHODS
#
#   X11 OPTION DATABASE ATTRIBUTES
#
#
# ----------------------------------------------------------------------

class SrcToolBar {
  inherit GDBToolBar

  # ------------------------------------------------------------------
  #  CONSTRUCTOR - create widget
  # ------------------------------------------------------------------
  constructor {src args} {
    set source $src
    _load_images
    _load_src_images

    create_buttons
    toolbar_show

    eval itk_initialize $args
    add_hook gdb_idle_hook "$this enable_ui 1"
    add_hook gdb_busy_hook "$this enable_ui 0"
    add_hook gdb_no_inferior_hook "$this enable_ui 2"
    add_hook gdb_trace_find_hook "$this handle_trace_find_hook"
  }

  # ------------------------------------------------------------------
  #  DESTRUCTOR - destroy window containing widget
  # ------------------------------------------------------------------
  destructor {
    global GDBSrcBar_state

    unset GDBSrcBar_state($this)
    remove_hook gdb_idle_hook "$this enable_ui 1"
    remove_hook gdb_busy_hook "$this enable_ui 0"
    remove_hook gdb_no_inferior_hook "$this enable_ui 2"
    remove_hook gdb_trace_find_hook "$this handle_trace_find_hook"

    #destroy $this
  }

  ####################################################################
  # The next set of functions are the generic button groups that gdb uses.
  # Private.  Used at contruction time.
  # These were previously at the GDBToolBar...
  ####################################################################
  
  # ------------------------------------------------------------------
  #  METHOD:  create_buttons - Add some buttons to the toolbar.
  #                         Returns list of buttons in form acceptable
  #                         to standard_toolbar.
  # ------------------------------------------------------------------
  private  method create_buttons {} {
    global enable_external_editor

    toolbar_add_button stop None {} {}
    _set_runstop

    if {[pref get gdb/mode]} {
      toolbar_add_button tstop Control \
                         [list $this do_tstop] "Start Collection" \
	                 -image Movie_on_img

      toolbar_add_button view Other [list $this set_control_mode 1] \
	                 "Switch to Browse Mode" -image watch_movie_img

      toolbar_add_button_separator

    }

    if {[pref get gdb/control_target]} {
      create_control_buttons
      if {[pref get gdb/mode]} {
	create_trace_buttons 0
      }
    } elseif {[get pref gdb/mode]} {

      #
      # If we don't control the target, then we might as well
      # put a copy of the trace controls on the source window.
      #
      create_trace_buttons 1
   }

    toolbar_add_button_separator

    create_window_buttons

    # Random bits of obscurity...
    toolbar_bind_button reg   <Button-3> "ManagedWin::open RegWin -force"
    toolbar_bind_button mem   <Button-3> "ManagedWin::open MemWin -force"
    toolbar_bind_button watch <Button-3> "ManagedWin::open WatchWin -force"
    toolbar_bind_button vars  <Button-3> "ManagedWin::open LocalsWin -force"

    toolbar_add_button_separator

    if {[info exists enable_external_editor] && $enable_external_editor} {
      toolbar_add_button edit Other [code $source edit] "Edit Source" \
	                      -image edit_img

      toolbar_add_button_separator
    }

    toolbar_add_label addr $address "Address" -width 10 -relief sunken \
                           -bd 1 -anchor e -font  src-font

    toolbar_add_label line $line "Line Number" -width 6 -relief sunken \
                           -bd 1 -anchor e -font  src-font

    toolbar_button_right_justify

    create_stack_buttons

    # This feature has been disabled for now.
    # checkbutton $ButtonFrame.upd -command "$this _toggle_updates" \
    #   -variable GDBSrcBar_state($this)
    # lappend button_list $ButtonFrame.upd
    # global GDBSrcBar_state
    # ::set GDBSrcBar_state($this) $updatevalue
    # balloon register $ButtonFrame.upd "Toggle Window Updates"
  }

  # ------------------------------------------------------------------
  #  METHOD:  create_control_buttons - Creates the step, continue, etc buttons.
  # ------------------------------------------------------------------
  
  private method create_control_buttons {} {
    toolbar_add_button step Control [code $source inferior step] \
      "Step (S)" -image step_img
    
    toolbar_add_button next Control [code $source inferior next] \
      "Next (N)" -image next_img
    
    toolbar_add_button finish Control [code $source inferior finish] \
      "Finish (F)" -image finish_img
    
    toolbar_add_button continue Control [code $source inferior continue] \
      "Continue (C)" -image continue_img
    
    # A spacer before the assembly-level items looks good.  It helps
    # to indicate that these are somehow different.
    toolbar_add_button_separator
    
    toolbar_add_button stepi Control [code $source inferior stepi] \
      "Step Asm Inst (S)" -image stepi_img
    
    toolbar_add_button nexti Control [code $source inferior nexti] \
      "Next Asm Inst (N)" -image nexti_img
    
    _set_stepi

    set Run_control_buttons {step next finish continue -stepi nexti}
    
  }

  # ------------------------------------------------------------------
  #  METHOD:  create_trace_buttons - Creates the next hit, etc.
  # ------------------------------------------------------------------
  
  private method create_trace_buttons {{show 0}} {

    if {$show} {
      set command toolbar_add_button
    } else {
      set command toolbar_create_button
    }

    $command tfindstart Trace {tfind_cmd "tfind start"} "First Hit <F>" \
      -image rewind_img
    
    $command tfind Trace {tfind_cmd tfind} "Next Hit <N>" -image next_hit_img
    
    $command tfindprev Trace {tfind_cmd "tfind -"} "Previous Hit <P>" \
      -image prev_hit_img
    
    $command tfindline Trace {tfind_cmd "tfind line"} "Next Line Hit <L>" \
      -image next_line_img
    
    $command tfindtp Trace { tfind_cmd "tfind tracepoint"} \
      "Next Hit Here <H>" -image next_check_img

    set Trace_control_buttons {tfindstart tfind tfindprev tfindline tfindtp}
  }

  # ------------------------------------------------------------------
  #  METHOD:  create_window_buttons - Creates the registers, etc, buttons
  # ------------------------------------------------------------------
  
  private method create_window_buttons {} {
    toolbar_add_button reg Other {ManagedWin::open RegWin} \
                           "Registers (Ctrl+R)" -image reg_img

    toolbar_add_button mem Other {ManagedWin::open MemWin} \
                           "Memory (Ctrl+M)" -image memory_img

    toolbar_add_button stack Other {ManagedWin::open StackWin} \
                             "Stack (Ctrl+S)" -image stack_img

    toolbar_add_button watch Other {ManagedWin::open WatchWin} \
                             "Watch Expressions (Ctrl+W)" -image watch_img

    toolbar_add_button vars Other {ManagedWin::open LocalsWin} \
                            "Local Variables (Ctrl+L)" -image vars_img

    if {[pref get gdb/control_target]} {
      toolbar_add_button bp Other {ManagedWin::open BpWin} \
                            "Breakpoints (Ctrl+B)" -image bp_img
    }

    if {[pref get gdb/mode]} {
      toolbar_add_button tp Other {ManagedWin::open BpWin -tracepoints 1} \
	"Tracepoints (Ctrl+T)" -image tp_img
      
      toolbar_add_button tdump Trace {ManagedWin::open TdumpWin} \
                               "Tdump (Ctrl+D)" -image tdump_img
    }

    toolbar_add_button con Other {ManagedWin::open Console} \
                           "Console (Ctrl+N)" -image console_img
  }

  # ------------------------------------------------------------------
  #  METHOD:  create_stack_buttons - Creates the up down bottom stack buttons
  # ------------------------------------------------------------------
  
  private method create_stack_buttons {} {

    toolbar_add_button down {Trace Control} \
      [code $source stack down] \
      "Down Stack Frame" -image down_img

    toolbar_add_button up {Trace Control} \
      [code $source stack up] \
      "Up Stack Frame" -image up_img

    toolbar_add_button bottom {Trace Control} \
      [code $source stack bottom] \
      "Go to Bottom of Stack" -image bottom_img

  }

  ####################################################################
  # 
  ####################################################################

  # ------------------------------------------------------------------
  #  METHOD:  _load_images - Load standard images.  Private method.
  # ------------------------------------------------------------------
  public method _load_images { {reconfig 0} } {
    global gdb_ImageDir
    if {!$reconfig && $_loaded_images} {
      return
    }
    set _loaded_images 1

    lappend imgs console reg stack vmake vars watch memory bp
    foreach name $imgs {
      image create photo ${name}_img -file [file join $gdb_ImageDir ${name}.gif]
    }
  }

  # ------------------------------------------------------------------
  #  METHOD:  _load_src_images - Load standard images.  Private method.
  # ------------------------------------------------------------------
  method _load_src_images { {reconf 0} } {
    global gdb_ImageDir

    if {!$reconf && $_loaded_src_images} {
      return
    }
    set _loaded_src_images 1

    foreach name {run stop step next finish continue edit \
		    stepi nexti up down bottom Movie_on Movie_off \
		    next_line next_check next_hit rewind prev_hit \
		  watch_movie run_expt tdump tp} {
      image create photo ${name}_img -file [file join $gdb_ImageDir ${name}.gif]
    }
  }

  # ------------------------------------------------------------------
  #  METHOD:  _set_runstop - Set state of run/stop button.
  #
  #  busy        - Run button becomes disabled
  #  running     - Stop button appears, allowing user to stop executing target
  #  downloading - Stop button appears, allowing user to interrupt downloading
  #  normal      - Run button appears, allowing user to run/re-run exe
  # ------------------------------------------------------------------
  public method _set_runstop {} {
    dbug W $runstop

    switch $runstop {
      busy {
	toolbar_configure_button stop -state disabled
      }
      downloading {
	toolbar_configure_button stop -state normal -image stop_img \
	  -command [code $this cancel_download]
	toolbar_set_button_balloon stop "Stop"
      }
      running {
	toolbar_configure_button stop -state normal -image stop_img \
	  -command [code $source inferior stop]
	toolbar_set_button_balloon stop "Stop"
      }
      normal {
	toolbar_configure_button stop -state normal -image run_img \
	  -command [code $source inferior run]
	toolbar_set_button_balloon stop "Run (R)"
      }
      default {
	dbug W "unknown state $runstop"
      }
    }
  }


  # ------------------------------------------------------------------
  #  METHOD:  _set_stepi - Set state of stepi/nexti buttons.
  # ------------------------------------------------------------------
  public method _set_stepi {} {
    
    # Only do this in synchronous mode
    if {!$Tracing} {
      # In source-only mode, disable these buttons.  Otherwise, enable
      # them.
      if {$displaymode == "SOURCE"} {
	set state disabled
      } else {
	set state normal
      }
      toolbar_configure_button stepi -state $state
      toolbar_configure_button nexti -state $state
    }
  }

  # ------------------------------------------------------------------
  #  METHOD:  handle_trace_find_hook - response to the tfind command.
  #             If the command puts us in a new mode, then switch modes...
  # ------------------------------------------------------------------
  method handle_trace_find_hook {mode from_tty} {
    debug "mode: $mode, from_tty: $from_tty, Browsing: $Browsing"
    if {[string compare $mode -1] == 0} {
      if {$Browsing} {
	set_control_mode 0
      }
    } else {
      if {!$Browsing} {
	set_control_mode 1
      }
    }
  }

  # ------------------------------------------------------------------
  #  METHOD:  set_control_mode - sets up the srcbar for browsing 
  #  a trace experiment.
  #   mode: 1 => browse mode
  #         0 => control mode
  # ------------------------------------------------------------------
  method set_control_mode  {mode} {
    debug "set_control_mode called with mode $mode"
    if {$mode} {
      set Browsing 1
      toolbar_configure_button view -image run_expt_img \
                            -command "$this set_control_mode 0"
      toolbar_set_button_balloon view "Switch to Control mode"
      # Now swap out the buttons...
      toolbar_swap_button_lists $Trace_control_buttons $Run_control_buttons
      enable_ui 1
    } else {
      if {$Browsing} {
	tfind_cmd {tfind none}
      }
      set Browsing 0
      toolbar_configure_button view -image watch_movie_img \
                            -command "$this set_control_mode 1"
      toolbar_set_button_balloon view "Switch to Browse mode"
      # Now swap out the buttons...
      toolbar_swap_button_lists $Run_control_buttons $Trace_control_buttons
      enable_ui 1
    }
    run_hooks control_mode_hook $Browsing
  }

  # ------------------------------------------------------------------
  #  METHOD:  _toggle_updates - Run when the update checkbutton is
  #                             toggled.  Private method.
  # ------------------------------------------------------------------
  public method _toggle_updates {} {
    global GDBSrcBar_state
    if {$updatecommand != ""} {
      uplevel \#0 $updatecommand $GDBSrcBar_state($this)
    }
  }

  # ------------------------------------------------------------------
  #  METHOD:  cancel_download
  # ------------------------------------------------------------------
  public method cancel_download {} {
    global download_dialog download_cancel_ok

    if {"$download_dialog" != ""} {
      $download_dialog cancel
    } else {
      set download_cancel_ok 1
    }
  }

  # ------------------------------------------------------------------
  #  METHOD:  reconfig - reconfigure the srcbar
  #                      used when preferences change
  # ------------------------------------------------------------------
  public method reconfig {} {
    debug
    _load_src_images 1
    _load_images 1
    # FIXME: Must Check if we are Tracing and set the buttons accordingly.
  }

  # ------------------------------------------------------------------
  # METHOD:  do_tstop: Change the GUI state, then do the tstop or
  #                    tstart command, whichever is appropriate.   
  #   
  # ------------------------------------------------------------------
  method do_tstop {} {
    debug "do_tstop called... Collecting is $Collecting"

    # FIXME: This must be done in conjunction with the menu or the
    # states will mismatch.

    if {!$Collecting} {
      #
      # Start the trace experiment
      #

      if {$Browsing} {
	set ret [tk_messageBox -title "Warning" -message \
"You are currently browsing a trace experiment. 
This command will clear the results of that experiment.
Do you want to continue?" \
		   -icon warning -type okcancel -default ok]
	if {[string compare $ret cancel] == 0} {
	  return
	}
	set_control_mode 1
      }
      if {[tstart]} {
	toolbar_configure_button tstop -image Movie_off_img
	toolbar_set_button_balloon tstop "End Collection"
	set Collecting 1
      } else {
	tk_messageBox -title Error -message "Error downloading tracepoint info" \
	  -icon error -type ok
      }
    } else {
      #
      # Stop the trace experiment
      #

      if {[tstop]} {	
	toolbar_configure_button tstop -image Movie_on_img
	toolbar_set_button_balloon tstop "Start Collection"
	set Collecting 0
     }
    }
  }

  ####################################################################
  # The following method enables/disables both menus and buttons.
  ####################################################################

  # ------------------------------------------------------------------
  # METHOD:  enable_ui - enable/disable the appropriate buttons and menus
  # Called from the busy, idle, and no_inferior hooks.
  #
  # on must be:
  # value      Control    Other    Trace    State
  #   0          off       off      off     gdb is busy
  #   1          on        on       off     gdb has inferior, and is idle
  #   2          off       on       off     gdb has no inferior, and is idle
  # ------------------------------------------------------------------
  public method enable_ui {on} {
    global tcl_platform
    debug "$on - Browsing=$Browsing"

    # Do the enabling so that all the disabling happens first, this way if a
    # button belongs to two groups, enabling takes precedence, which is probably right.

    switch $on {
      0 {
        # Busy
	set enable_list {Control disabled \
			   Other disabled \
			   Trace disabled \
			   Attach disabled \
			   Detach disabled}
      }
      1 {
        # Idle, with inferior
	if {!$Browsing} {
	  set enable_list {Trace disabled \
			     Control normal \
			     Other normal \
			     Attach disabled \
			     Detach normal }
	  # set the states of stepi and nexti correctly
	  _set_stepi
	} else {
	  set enable_list {Control disabled Other normal Trace normal}
	}

      }
      2 {
        # Idle, no inferior
	set enable_list {Control disabled \
			   Trace disabled \
			   Other normal \
			   Attach normal \
			   Detach disabled }
      }
      default {
	debug "Unknown type: $on in enable_ui"
	return
      }
    }

    set_class_state $enable_list
  }

  ####################################################################
  #
  #  PRIVATE DATA
  #
  ####################################################################

  # This is a handle on our parent source window.
  private variable source {}

  #
  # FIXME - Need to break the images into the sets needed for
  # each button group, and load them when the button group is
  # created.

  # This is set if we've already loaded the standard images.
  private common _loaded_images 0

  # This is set if we've already loaded the standard images.  Private
  # variable.
  private common _loaded_src_images 0

  # These buttons go in the control area when we are browsing
  protected variable Trace_control_buttons 

  # And these go in the control area when we are running
  protected variable Run_control_buttons

  ####################################################################
  #
  #  PUBLIC DATA
  #
  ####################################################################

  # This is the command that should be run when the `update'
  # checkbutton is toggled.  The current value of the checkbutton is
  # appended to the command.
  public variable updatecommand {}

  # This controls whether the `update' checkbutton is turned on or
  # off.
  public variable updatevalue 0 {
    global GDBSrcBar_state
    ::set GDBSrcBar_state($this) $updatevalue
  }

  # This holds the text that is shown in the address label.
  public variable address {} {
    toolbar_configure_button addr -text $address -font src-font
  }

  # This holds the text that is shown in the line label.
  public variable line {} {
    toolbar_configure_button line -text $line
  }

  # This holds the source window's display mode.  Valid values are
  # SOURCE, ASSEMBLY, SRC+ASM, and MIXED.
  public variable displaymode SOURCE {
    _set_stepi
  }

  # This indicates what is the inferior state.
  # Possible values are: {busy running downloading normal}
  public variable runstop normal {
    dbug W "configuring runstop $runstop"

    # Set the Run/Stop button accordingly
    _set_runstop
  }

  # The next three determine the state of the application when Tracing is enabled.

  public variable Tracing 0     ;# Is tracing enabled for this gdb?
  public variable Browsing   0  ;# Are we currently browsing a trace experiment?
  public variable Collecting 0  ;# Are we currently collecting a trace experiment?
}
