Showing posts with label clean code. Show all posts
Showing posts with label clean code. Show all posts

Saturday, July 26, 2025

handle_key_press - the "Monster Function"

> How do you recommend going after the monster function handle_key_press?

● Excellent question! The handle_key_press() function with 1,524 lines is a prime example of what needs systematic refactoring.

  Let me analyze it and provide a concrete attack strategy.

● Update Todos

  ⎿  ☐ Analyze handle_key_press function structure

     ☐ Identify key functional groups and responsibilities

     ☐ Design refactoring strategy with safe incremental steps

     ☐ Test and validate refactored implementation

     ☐ Create helper function extraction plan

     ☐ Implement command dispatch table approach

● Strategic Attack Plan for handle_key_press() Monster Function

  Based on my analysis, here's my recommended safe, incremental refactoring strategy:

  🎯 Phase 1: Extract Helper Functions (Low Risk)

  Start with the most duplicated code to get immediate wins:

  1.1 Extract Layer Selection Logic

  static void handle_layer_selection(int layer_num) {
      char n[30];
      xctx->rectcolor = layer_num;
      my_snprintf(n, S(n), "%d", xctx->rectcolor);
      tclvareval("xschem set rectcolor ", n, NULL);
      /* ... reconfigure_layers_button logic ... */
  }
  Impact: Eliminates ~200 lines of duplication across numeric keys.

  1.2 Extract Common Patterns

  static int should_handle_key(int event, KeySym key, int state, int button) {
      if(xctx->semaphore >= 2) return 0;
      if(waves_selected(event, key, state, button)) {
          waves_callback(event, mx, my, key, button, aux, state);
          return 0;
      }
      return 1;
  }

  static void start_move_operation(int infix_interface) {
      if(infix_interface) {
          xctx->mx_double_save = xctx->mousex_snap;
          xctx->my_double_save = xctx->mousey_snap;
          move_objects(START,0,0,0);
      } else {
          xctx->ui_state |= MENUSTART;
          xctx->ui_state2 = MENUSTARTMOVE;
      }
  }

  🎯 Phase 2: Key Group Extraction (Medium Risk)

  Extract logical groups one at a time, testing thoroughly:

  2.1 Start with Numeric Keys (Safest)

  static void handle_numeric_keys(KeySym key, int state, int rstate) {
      if(rstate == 0) {
          /* Logic level setting */
          if(key >= '0' && key <= '9') {
              handle_layer_selection((int)key - '0');
              return;
          }
      }
      else if(rstate == ControlMask) {
          /* Layer selection with Ctrl */
          // ... existing logic
      }
  }

  2.2 Extract File Operations

  static void handle_file_keys(KeySym key, int state, int rstate,
                              int infix_interface, const char *win_path) {
      switch(key) {
          case 's': handle_save_operation(state); break;
          case 'S': handle_save_as_operation(); break;
          case 'o': handle_open_operation(); break;
          // ... etc
      }
  }

  🎯 Phase 3: Command Dispatch Table (Higher Risk)

  Replace the massive switch with a cleaner dispatch system:

  3.1 Define Key Handler Structure

  typedef struct {
      KeySym key;
      int modifier_mask;
      void (*handler)(KeyHandlerContext *ctx);
      const char *description;
  } KeyHandler;

  typedef struct {
      int event, state, rstate, mx, my, button, aux;
      int infix_interface, enable_stretch, cadence_compat;
      int wire_draw_active, snap_cursor;
      const char *win_path;
      double c_snap;
      KeySym key;
  } KeyHandlerContext;

  3.2 Create Handler Table

  static const KeyHandler key_handlers[] = {
      {'w', 0, handle_place_wire, "Place wire"},
      {'W', 0, handle_place_snapped_wire, "Place snapped wire"},
      {'c', 0, handle_copy, "Copy selection"},
      {'m', 0, handle_move, "Move selection"},
      // ... hundreds of entries
      {0, 0, NULL, NULL} // terminator
  };

  static void handle_key_press_new(/* same params */) {
      KeyHandlerContext ctx = {/* initialize from params */};

      if(!should_handle_key(event, key, state, button)) return;

      for(const KeyHandler *h = key_handlers; h->handler; h++) {
          if(h->key == key && (state & h->modifier_mask) == h->modifier_mask) {
              h->handler(&ctx);
              return;
          }
      }

      // Handle unmapped keys
      handle_unmapped_key(&ctx);
  }

  🎯 Recommended Step-by-Step Attack Plan

  Week 1-2: Quick Wins (Helper Functions)

  1. ✅ Extract handle_layer_selection()
  2. ✅ Extract should_handle_key()
  3. ✅ Extract start_move_operation(), start_copy_operation()
  4. ✅ Extract rotation/flip helpers
  5. ✅ Run full regression tests

  Expected Impact: ~400 lines reduced, 0% risk of breaking functionality

  Week 3-4: First Group Extraction

  1. ✅ Extract handle_numeric_keys() (safest group)
  2. ✅ Extract handle_system_keys() (Delete, Escape, Return, etc.)
  3. ✅ Thorough testing with focus on these key groups
  4. ✅ Update any affected documentation

  Expected Impact: ~300 lines reduced, <5% risk

  Week 5-6: Core Groups

  1. ✅ Extract handle_file_keys() (save, load, etc.)
  2. ✅ Extract handle_navigation_keys() (zoom, pan)
  3. ✅ Extract handle_drawing_keys() (wire, line, arc)
  4. ✅ Intensive testing of drawing operations

  Expected Impact: ~600 lines reduced, 10% risk

  Week 7-8: Complex Groups

  1. ✅ Extract handle_selection_keys() (copy, move, select)
  2. ✅ Extract handle_transformation_keys() (rotate, flip)
  3. ✅ Extract handle_net_keys() (highlighting, tracing)
  4. ✅ Performance testing (these are hot paths)

  Expected Impact: ~400 lines reduced, 15% risk

  Week 9-10: Cleanup and Optimization

  1. ✅ Consider dispatch table approach for remaining keys
  2. ✅ Extract handle_special_keys() for symbols
  3. ✅ Final integration testing
  4. ✅ Performance benchmarks vs. original

  Final Result: 1,524 lines → ~200 lines main function + ~1,300 lines in focused modules

  🛡️ Risk Mitigation Strategies

  Safety Measures

  1. Git branching: Each phase gets its own branch
  2. Regression testing: Full test suite after each extraction
  3. Performance testing: Ensure no keystroke latency increase
  4. User testing: Have power users test drawing operations
  5. Rollback plan: Keep original function as handle_key_press_legacy() initially

  Testing Strategy

  1. Unit tests: Each extracted function gets unit tests
  2. Integration tests: Full drawing workflows
  3. Performance tests: Keystroke latency measurements
  4. Edge case tests: Modifier combinations, rapid key sequences
  5. Memory tests: Check for leaks in new function boundaries

  🎉 Benefits of This Approach

  Immediate Benefits (Phase 1)

  - ✅ Eliminates massive code duplication
  - ✅ Makes individual key handlers readable
  - ✅ Zero functional risk

  Medium-term Benefits (Phase 2)

  - ✅ Function becomes navigable and maintainable
  - ✅ New key handlers become trivial to add
  - ✅ Unit testing becomes possible

  Long-term Benefits (Phase 3)

  - ✅ Self-documenting key binding system
  - ✅ Runtime key remapping becomes possible
  - ✅ Help system can auto-generate from handler table
  - ✅ Plugin system for custom key handlers

  This phased approach gives you immediate wins while building toward a professional-grade architecture with minimal risk to the
  critical user interaction code.

Stefan++ : How? Reduce Cyclomatic Complexity

What does "high cyclomatic complexity" mean?

It means your code has turned into a labyrinth, and anyone trying to maintain it will likely curse your name.

Cyclomatic complexity is a metric that counts the number of independent paths through your code. Think of it as a "how many ways can I break my brain" counter. The higher the number, the more branches, loops, and conditionals are cluttering up your code.

  • Low cyclomatic complexity (1–10): Code is simple, readable, and probably written by someone who still has hope.
  • High cyclomatic complexity (20+): Code is a minefield of if statements, while loops, and spaghetti logic.

In short, “high cyclomatic complexity” means your code is doing too much in one place and needs to be refactored into smaller, cleaner chunks.

Checklist: How to Reduce Cyclomatic Complexity

✅ 1. Split Large Functions

Break big functions into smaller, focused ones.

def process_order(order):
    if order.type == 'online':
        ...
    elif order.type == 'in-store':
        ...

# Better:
def process_order(order):
    if order.type == 'online':
        handle_online(order)
    elif order.type == 'in-store':
        handle_instore(order)

✅ 2. Replace Complex Conditionals with Polymorphism

# Bad:
if shape == 'circle':
    ...
elif shape == 'square':
    ...

# Better:
class Shape:
    def area(self): pass

class Circle(Shape):
    def area(self): return pi * r * r

✅ 3. Use Guard Clauses

# Instead of:
def process(user):
    if user.is_active:
        if user.has_permission:
            ...

# Do:
def process(user):
    if not user.is_active or not user.has_permission:
        return
    ...

✅ 4. Use Lookups Instead of Conditionals

# Instead of:
if key == 'a': do_a()
elif key == 'b': do_b()

# Do:
actions = {'a': do_a, 'b': do_b}
actions.get(key, do_default)()

✅ 5. Extract Logic from Loops

# Instead of:
for item in items:
    if item.is_valid() and not item.is_expired():
        if item.value > threshold:
            ...

# Do:
for item in items:
    handle_item(item)

✅ 6. Minimize Boolean Logic

# Instead of:
if not (x or (y and not z)):

# Do:
should_skip = x or (y and not z)
if not should_skip:
Code copied!


And the oracle sayeth:


✅ Strengths

  • Feature-Rich Logic:
    • The code accounts for many interaction scenarios: object selection, dragging, wire drawing, copying, and stretching with modifier keys.
    • It provides support for both Cadence-compatibility and an intuitive UX mode.
  • Clear Modular Function Calls:
    • Core behaviors are abstracted into well-named helper functions like select_object(), unselect_all(), add_wire_from_wire(), edit_rect_point() etc., improving readability.
  • State-Sensitive Logic:
    • Thorough checks on modifier keys (Shift, Ctrl) allow nuanced control over actions.
  • Debug Logging:
    • Multiple dbg() calls provide useful tracepoints during development or troubleshooting.

⚠️ Issues

1. Complexity / Spaghetti Logic

  • The if(...) block is far too long and complex. It’s trying to do too many things: selection logic, wire and polygon editing, dragging, duplication, net highlighting.
  • Deep nesting (especially conditionals like if(xctx->intuitive_interface && !already_selected && no_shift_no_ctrl)) makes it hard to parse.

2. Poor Naming / Use of Magic Constants

  • The macro START_W_A_L_P_R is opaque — its purpose is unclear.
  • sel.type == 0 — unclear what type 0 means.
  • No enums or typedefs are shown for sel.type — numeric constants make code harder to read.

3. Repeated Conditions

  • Checks like if(xctx->intuitive_interface && !already_selected) are repeated multiple times in a row — should be grouped.

4. Missing or Implicit Documentation

  • There are comments, but many conditionals aren’t well explained. For example, why already_selected matters so much in certain branches.
  • The purpose of the shape_point_selected logic and its interaction with drag is not made very clear.

5. Potential Redundant Operations

  • rebuild_selected_array() is always called after selection — is it needed even if no selection occurred?

6. Mutable Global State via xctx

  • Heavy use of xctx-> everywhere — likely a global or shared context. Makes testing and reasoning harder.

7. Poor Separation of Concerns

  • UI selection, editing logic, and net handling (highlighting) are all interwoven. This should be split into clearer stages or functions.

💡 Recommendations

✅ Refactor: Break Into Smaller Functions

void handle_wire_drawing(...);
void handle_object_selection(...);
void handle_drag_or_copy(...);
void handle_net_highlighting(...);

✅ Use Enums for Object Types

typedef enum {
    OBJ_NONE = 0,
    OBJ_POLYGON,
    OBJ_LINE,
    OBJ_WIRE,
    OBJ_RECT,
    ...
} ObjectType;

✅ Simplify Modifier Logic

bool is_ctrl_pressed = state & ControlMask;
bool is_shift_pressed = state & ShiftMask;

Then use these throughout to improve readability.

✅ Avoid Code Duplication

if(xctx->intuitive_interface && !already_selected) {
    if(add_wire_from_inst(...) || add_wire_from_wire(...)) return;
}

✅ Abstract shape_point_selected logic

Handle that check and invocation in a single, cleaner function like:

bool try_select_shape_point(int state);

🧹 Minor Cleanup

  • The outer if(!START_W_A_L_P_R && !(xctx->ui_state & STARTSELECT)) is a mouthful. Consider making a helper function like:
    bool is_ui_start_state_ok(...) { ... }
  • Comments like /* if dragging instances with stretch enabled and Shift down add wires... */ are helpful but would be better expressed via well-named helper functions.

✨ Summary

This code is functionally robust but structurally messy. It’s very common in UI-heavy C codebases, but would benefit immensely from decomposition, naming improvements, and state isolation. The functionality is all there — it just needs clarity to become maintainable.

Want help drafting a refactored version of this block?

Thursday, March 20, 2025

chatGPT on handle_button_press

The agony:

static void handle_button_press(int event, int state, int rstate, KeySym key, int button, int mx, int my,
                                double c_snap, int draw_xhair, int crosshair_size, int enable_stretch, int aux)
{
   int use_cursor_for_sel = tclgetintvar("use_cursor_for_selection");
   int excl = xctx->ui_state & (STARTWIRE | STARTRECT | STARTLINE | STARTPOLYGON | STARTARC);
   dbg(1, "callback(): ButtonPress  ui_state=%d state=%d\n",xctx->ui_state,state);
   if(waves_selected(event, key, state, button)) {
     waves_callback(event, mx, my, key, button, aux, state);
     return;
   }
   /* terminate a schematic pan action */
   if(xctx->ui_state & STARTPAN) {
     xctx->ui_state &=~STARTPAN;
     return;
   }

   /* select instance and connected nets stopping at wire junctions */
   if(!excl && button == Button3 && state == ControlMask && xctx->semaphore <2)
   {
     Selected sel;
     sel = select_object(xctx->mousex, xctx->mousey, SELECTED, 0, NULL);
     if(sel.type) select_connected_nets(1);
   }
   
   /* break wire at mouse coordinates, move break point to nearest grid point */
   else if(!excl && button == Button3 && EQUAL_MODMASK &&
           !(state & ShiftMask) && xctx->semaphore <2)
   {
     break_wires_at_point(xctx->mousex_snap, xctx->mousey_snap, 1);
   }
   /* break wire at mouse coordinates */
   else if(!excl && button == Button3 && EQUAL_MODMASK &&
           (state & ShiftMask) && xctx->semaphore <2)
   {
     break_wires_at_point(xctx->mousex_snap, xctx->mousey_snap, 0);
   }
   /* select instance and connected nets NOT stopping at wire junctions */
   else if(!excl && button == Button3 && state == ShiftMask && xctx->semaphore <2)
   {
     Selected sel;
     sel = select_object(xctx->mousex, xctx->mousey, SELECTED, 0, NULL);
     if(sel.type) select_connected_nets(0);
   }
   /* moved to Button3 release */
   /*
    * else if(button == Button3 && state == 0 && xctx->semaphore <2) {
    *   context_menu_action(xctx->mousex_snap, xctx->mousey_snap);
    * }
    */

   /* zoom rectangle by right clicking and drag */
   else if(!excl && button == Button3 && state == 0 && xctx->semaphore < 2) {
     zoom_rectangle(START);return;
   }
     
   /* Mouse wheel events */
   else if(handle_mouse_wheel(event, mx, my, key, button, aux, state)) return;

   /* terminate wire placement in snap mode */
   else if(button==Button1 && (state & ShiftMask) && (xctx->ui_state & STARTWIRE) ) {
     snapped_wire(c_snap);
   }
   /* Alt - Button1 click to unselect */
   else if(button==Button1 && (SET_MODMASK) ) {
     unselect_at_mouse_pos(mx, my);
   }
   
   /* Middle button press (Button2) will pan the schematic. */
   else if(button==Button2 && (state == 0)) {
     pan(START, mx, my);
     xctx->ui_state |= STARTPAN;
   }

   /* button1 click to select another instance while edit prop dialog open */
   else if(button==Button1 && xctx->semaphore >= 2) {
     if(tcleval("winfo exists .dialog.textinput")[0] == '1') { /* proc text_line */
       tcleval(".dialog.f1.b1 invoke");
       return;
     } else if(tcleval("winfo exists .dialog.txt")[0] == '1') { /* proc enter_text */
       tcleval(".dialog.buttons.ok invoke");
       return;
     } else if(state==0 && tclgetvar("edit_symbol_prop_new_sel")[0]) {
       tcleval("set edit_symbol_prop_new_sel 1; .dialog.f1.b1 invoke"); /* invoke 'OK' of edit prop dialog */
     } else if((state & ShiftMask) && tclgetvar("edit_symbol_prop_new_sel")[0]) {
       select_object(xctx->mousex, xctx->mousey, SELECTED, 0, NULL);
       tclsetvar("preserve_unchanged_attrs", "1");
       rebuild_selected_array();
     }
   }

   /* Handle the remaining Button1Press events */
   else if(button==Button1) /* MOD button is not pressed here. Processed above */
   {
     xctx->onetime = 0;
     xctx->mouse_moved = 0;
     xctx->drag_elements = 0;

     /* start another wire or line in persistent mode */
     if(tclgetboolvar("persistent_command") && xctx->last_command) {
       if(xctx->last_command == STARTLINE)  start_line(xctx->mousex_snap, xctx->mousey_snap);
       if(xctx->last_command == STARTWIRE){
        if(tclgetboolvar("snap_cursor")
             && (xctx->prev_snapx == xctx->mousex_snap
             && xctx->prev_snapy == xctx->mousey_snap)
             && (xctx->ui_state & STARTWIRE)
             && xctx->closest_pin_found){
          new_wire(PLACE|END, xctx->mousex_snap, xctx->mousey_snap);
          xctx->ui_state &= ~STARTWIRE;
        }
        else
          start_wire(xctx->mousex_snap, xctx->mousey_snap);
      }
        return;
     }
     /* handle all object insertions started from Tools/Edit menu */
     if(check_menu_start_commands(state, c_snap, mx, my)) return;

     /* complete the pending STARTWIRE, STARTRECT, STARTZOOM, STARTCOPY ... operations */
     if(end_place_move_copy_zoom()) return;

     /* Button1Press to select objects */
     if(!excl && !(xctx->ui_state & STARTSELECT)) {
       Selected sel;
       int already_selected = 0;
       int prev_last_sel = xctx->lastsel;
       int no_shift_no_ctrl = !(state & (ShiftMask | ControlMask));

       xctx->shape_point_selected = 0;
       xctx->mx_save = mx; xctx->my_save = my;
       xctx->mx_double_save=xctx->mousex;
       xctx->my_double_save=xctx->mousey;

       #if 0 /* disabled */
       /* Clicking and dragging from a **selected** instance pin will start a new wire
        * if no other elements are selected */
       if(xctx->lastsel == 1 && xctx->sel_array[0].type==ELEMENT) {
         if(add_wire_from_wire(&xctx->sel_array[0], xctx->mousex_snap, xctx->mousey_snap)) return;
         if(add_wire_from_inst(&xctx->sel_array[0], xctx->mousex_snap, xctx->mousey_snap)) return;
       }
       #endif

       /* In *NON* intuitive interface a button1 press with no modifiers will
        * first unselect everything...
        * For intuitive interface unselection see below... */
       if(!xctx->intuitive_interface && no_shift_no_ctrl ) unselect_all(1);

       /* find closest object. Use snap coordinates if full crosshair is enabled
        * since the mouse pointer is obscured and crosshair is snapped to grid points */
       if(draw_xhair && (use_cursor_for_sel || crosshair_size == 0)) {
         sel = find_closest_obj(xctx->mousex_snap, xctx->mousey_snap, 0);
       } else {
         sel = find_closest_obj(xctx->mousex, xctx->mousey, 0);
       }
       dbg(1, "sel.type=%d\n", sel.type);
       /* determine if closest object was already selected when button1 was pressed */
       switch(sel.type) {
         case WIRE:    if(xctx->wire[sel.n].sel)          already_selected = 1; break;
         case xTEXT:   if(xctx->text[sel.n].sel)          already_selected = 1; break;
         case LINE:    if(xctx->line[sel.col][sel.n].sel) already_selected = 1; break;
         case POLYGON: if(xctx->poly[sel.col][sel.n].sel) already_selected = 1; break;
         case xRECT:   if(xctx->rect[sel.col][sel.n].sel) already_selected = 1; break;
         case ARC:     if(xctx->arc[sel.col][sel.n].sel)  already_selected = 1; break;
         case ELEMENT: if(xctx->inst[sel.n].sel)          already_selected = 1; break;
         default: break;
       } /*end switch */

       /* Clicking and drag on an instance pin -> drag a new wire */
       if(xctx->intuitive_interface && !already_selected) {
         if(add_wire_from_inst(&sel, xctx->mousex_snap, xctx->mousey_snap)) return;  
       }
 
       /* Clicking and drag on a wire end -> drag a new wire */
       if(xctx->intuitive_interface && !already_selected) {
         if(add_wire_from_wire(&sel, xctx->mousex_snap, xctx->mousey_snap)) return;  
       }

       /* In intuitive interface a button1 press with no modifiers will
        *  unselect everything... we do it here */
       if(xctx->intuitive_interface && !already_selected && no_shift_no_ctrl )  unselect_all(1);

       /* select the object under the mouse and rebuild the selected array */
       if(!already_selected) select_object(xctx->mousex, xctx->mousey, SELECTED, 0, &sel);
       rebuild_selected_array();
       dbg(1, "Button1Press to select objects, lastsel = %d\n", xctx->lastsel);

       /* if clicking on some object endpoints or vertices set shape_point_selected
        * this information will be used in Motion events to draw the stretched vertices */
       if(xctx->lastsel == 1 && xctx->sel_array[0].type==POLYGON) {
         if(edit_polygon_point(state)) return; /* sets xctx->shape_point_selected */
       }
       if(xctx->lastsel == 1 && xctx->intuitive_interface) {
         int cond = already_selected;

         if(cond && xctx->sel_array[0].type==xRECT) {
           if(edit_rect_point(state)) return; /* sets xctx->shape_point_selected */
         }

         if(cond && xctx->sel_array[0].type==LINE) {
           if(edit_line_point(state)) return; /* sets xctx->shape_point_selected */
         }

         if(cond && xctx->sel_array[0].type==WIRE) {
          if(edit_wire_point(state)) return; /* sets xctx->shape_point_selected */
         }
       }
       dbg(1, "shape_point_selected=%d, lastsel=%d\n", xctx->shape_point_selected, xctx->lastsel);

       /* intuitive interface: directly drag elements */
       if(sel.type && xctx->intuitive_interface && xctx->lastsel >= 1 &&
          !xctx->shape_point_selected) {
         /* enable_stretch (from TCL variable) reverses command if enabled:
          * - move --> stretch move
          * - stretch move (with ctrl key) --> move
          */
         int stretch = (state & ControlMask ? 1 : 0) ^ enable_stretch;
         xctx->drag_elements = 1;
         /* select attached nets depending on ControlMask and enable_stretch */
         if(stretch) {
           select_attached_nets(); /* stretch nets that land on selected instance pins */
         }
         /* if dragging instances with stretch enabled and Shift down add wires to pins
          * attached to something */
         if((state & ShiftMask) && stretch) {
           xctx->connect_by_kissing = 2; /* 2 will be used to reset var to 0 at end of move */
           move_objects(START,0,0,0);
         }
         /* dragging away an object with Shift pressed is a copy (duplicate object) */
         else if(state & ShiftMask) copy_objects(START);
         /* else it is a normal move */
         else move_objects(START,0,0,0);
       }

       if(tclgetboolvar("auto_hilight") && !xctx->shape_point_selected) {
         if(!(state & ShiftMask) && xctx->hilight_nets && sel.type == 0 ) {
           if(!prev_last_sel) {
             redraw_hilights(1); /* 1: clear all hilights, then draw */
           }
         }
         hilight_net(0);
         if(xctx->lastsel) {
           redraw_hilights(0);
         }
       }
       return;
     } /* if(!excl) */
   } /* button==Button1 */
   
   return;
}

And the ecstasy:

Critique of C Code

1. Code Organization & Readability Issues

  • Too Many Nested Conditions: Many if-else conditions are deeply nested, making the code difficult to follow. This should be refactored using helper functions that clearly state their purpose.
  • Lack of Comments for Logical Sections: Some sections are well-commented, but others are cryptic. Inline comments should explain why conditions check multiple key/mouse combinations.
  • Long Function Length (~200+ lines): This function is too long. Ideally, a function should be concise and focused on a single task. Consider breaking it into smaller functions like:
    • handle_mouse_wheel_events()
    • handle_selection()
    • handle_wire_modifications()
    • handle_panning_and_zooming()
    • handle_drag_and_move()

2. Maintainability & Code Duplication

  • Repeated Condition Checks: Instead of repeating similar conditions, refactor them into a dedicated function:
    
    int is_right_click_event(int button, int state) {
        return (button == Button3 && state == ControlMask && xctx->semaphore < 2);
    }
    
    Then, use it like this:
    
    if (is_right_click_event(button, state)) {
        // Handle selection
    }
    
  • Repeated Calls to select_object(): This function is called in multiple places under similar conditions. Consider abstracting selection behavior into a helper function.

3. Performance Considerations

  • Checking Multiple Conditions in a Single if Block: Instead of:
    
    if(!excl && button == Button3 && EQUAL_MODMASK &&
       !(state & ShiftMask) && xctx->semaphore <2 code="">
    Consider defining a common state check:
    
    int is_mouse_event(int button, int state, int modmask) {
        return (!excl && button == Button3 && EQUAL_MODMASK && state == modmask && xctx->semaphore < 2);
    }
    
  • Repeated TCL Calls: Calls like tcleval("winfo exists .dialog.textinput") should be cached if they are expensive.

4. Consistency & Naming Issues

  • Inconsistent Naming Conventions:
    • Some variables use snake_case (mousex_snap), others use PascalCase (Selected sel).
    • Some macros/constants (EQUAL_MODMASK, SET_MODMASK) are in uppercase, while others (STARTWIRE) appear mixed.
  • Use More Descriptive Variable Names:
    • excl → selection_excluded
    • sel → selected_object
    • aux → extra_data

5. Edge Cases & Potential Bugs

  • Handling Invalid States: There are some checks for UI states, but what if xctx->ui_state has an unexpected value? It’s safer to include debug messages or default behavior.
  • Potential Uninitialized Variable (sel): Selected sel; should be initialized properly before use.
  • Hardcoded Magic Numbers (xctx->semaphore >= 2): Use named constants instead:
    
    #define SEMAPHORE_THRESHOLD 2
    if (xctx->semaphore >= SEMAPHORE_THRESHOLD) { ... }
    

6. Possible Refactoring

A possible structure after breaking down the function:


static void handle_button_press(int event, int state, int rstate, KeySym key, int button, int mx, int my,
                                double c_snap, int draw_xhair, int crosshair_size, int enable_stretch, int aux) 
{ 
    dbg(1, "callback(): ButtonPress  ui_state=%d state=%d
", xctx->ui_state, state);

    if (waves_selected(event, key, state, button)) {
        waves_callback(event, mx, my, key, button, aux, state);
        return;
    }

    if (handle_schematic_pan()) return;
    if (handle_wire_selection(button, state)) return;
    if (handle_mouse_wheel(event, mx, my, key, button, aux, state)) return;
    if (handle_symbol_property_dialog(button, state, mx, my)) return;
    if (handle_object_selection(button, state, mx, my, c_snap, draw_xhair, crosshair_size, enable_stretch)) return;
}

Final Thoughts

✅ Pros:

  • Covers all necessary button interactions for the schematic editor.
  • Includes a lot of functionality like selection, panning, and wire manipulation.
  • Well-commented in some parts.

❌ Cons & Areas for Improvement:

  • The function is too long and needs to be split into smaller functions.
  • Many nested conditions reduce readability.
  • Code duplication (e.g., repeated select_object() calls).
  • Performance inefficiencies (repeated tcleval() calls).
  • Inconsistent naming makes it harder to follow.

Overall, a great effort, but it needs serious refactoring for maintainability and readability! 🚀

Getting a Useful VcXsrv Crash Dump

Winner of the first Nobel Prize in Physics ❯ tell me how to do the VcXsrv shortcut that I currently have in my Startup folder so that we get...