<commit_before>import re

def handleDebuggerWarnings(config):
    if "MSVC" in config:
        try:
            popup = waitForObject("{text?='<html><head/><body>*' type='QLabel' unnamed='1' visible='1' window=':Symbol Server_Utils::CheckableMessageBox'}", 10000)
            symServerNotConfiged = ("<html><head/><body><p>The debugger is not configured to use the public "
                                    "<a href=\"http://support.microsoft.com/kb/311503\">Microsoft Symbol Server</a>. "
                                    "This is recommended for retrieval of the symbols of the operating system libraries.</p>"
                                    "<p><i>Note:</i> A fast internet connection is required for this to work smoothly. "
                                    "Also, a delay might occur when connecting for the first time.</p>"
                                    "<p>Would you like to set it up?</p></br></body></html>")
            if popup.text == symServerNotConfiged:
                test.log("Creator warned about the debugger not being configured to use the public Microsoft Symbol Server.")
            else:
                test.warning("Creator showed an unexpected warning: " + str(popup.text))
            clickButton(waitForObject("{text='No' type='QPushButton' unnamed='1' visible='1' window=':Symbol Server_Utils::CheckableMessageBox'}", 10000))
        except LookupError:
            pass # No warning. Fine.
    else:
        if "Release" in config and platform.system() != "Darwin":
            message = waitForObject("{container=':Qt Creator.DebugModeWidget_QSplitter' name='qt_msgbox_label' type='QLabel' visible='1'}", 20000)
            test.compare(message.text, "This does not seem to be a \"Debug\" build.\nSetting breakpoints by file name and line number may fail.")
            clickButton("{container=':Qt Creator.DebugModeWidget_QSplitter' text='OK' type='QPushButton' unnamed='1' visible='1'}")

def takeDebuggerLog():
    invokeMenuItem("Window", "Views", "Debugger Log")
    debuggerLogWindow = waitForObject("{container=':DebugModeWidget.Debugger Log_QDockWidget' type='Debugger::Internal::CombinedPane' unnamed='1' visible='1'}", 20000)
    debuggerLog = str(debuggerLogWindow.plainText)
    mouseClick(debuggerLogWindow, 5, 5, 0, Qt.LeftButton)
    activateItem(waitForObjectItem(openContextMenuOnTextCursorPosition(debuggerLogWindow),
                                   "Clear Contents"))
    waitFor("str(debuggerLogWindow.plainText)==''", 5000)
    invokeMenuItem("Window", "Views", "Debugger Log")
    return debuggerLog

# function to set breakpoints for the current project
# on the given file,line pairs inside the given dict
# the lines are treated as regular expression
def setBreakpointsForCurrentProject(filesAndLines):
    # internal helper for setBreakpointsForCurrentProject
    # double clicks the treeElement inside the given navTree
    # TODO: merge with doubleClickFile() from tst_qml_editor & move to utils(?)
    def __doubleClickFile__(navTree, treeElement):
        waitForObjectItem(navTree, treeElement)
        fileNamePattern = re.compile(".*\.(?P<file>(.*\\\..*)?)$")
        fileName = fileNamePattern.search(treeElement).group("file").replace("\\.", ".")
        doubleClickItem(navTree, treeElement, 5, 5, 0, Qt.LeftButton)
        mainWindow = waitForObject(":Qt Creator_Core::Internal::MainWindow")
        waitFor('fileName in str(mainWindow.windowTitle)', 5000)
        return fileName

    switchViewTo(ViewConstants.DEBUG)
    removeOldBreakpoints()
    if not filesAndLines or not isinstance(filesAndLines, dict):
        test.fatal("This function only takes a non-empty dict.")
        return False
    navTree = waitForObject("{type='Utils::NavigationTreeView' unnamed='1' visible='1' "
                            "window=':Qt Creator_Core::Internal::MainWindow'}", 20000)
    for curFile,curLine in filesAndLines.iteritems():
        fName = __doubleClickFile__(navTree, curFile)
        editor = getEditorForFileSuffix(curFile)
        if not placeCursorToLine(editor, curLine, True):
            return False
        invokeMenuItem("Debug", "Toggle Breakpoint")
        test.log('Set breakpoint in %s' % fName, curLine)
    breakPointTreeView = waitForObject("{type='Debugger::Internal::BreakWindow' visible='1' "
                                       "windowTitle='Breakpoints' name='Debugger.Docks.Break'}")
    waitFor("breakPointTreeView.model().rowCount() == len(filesAndLines)", 2000)
    test.compare(breakPointTreeView.model().rowCount(), len(filesAndLines),
                 'Expected %d set break points, found %d listed' %
                 (len(filesAndLines), breakPointTreeView.model().rowCount()))
    return True

# helper that removes all breakpoints - assumes that it's getting called
# being already on Debug view and Breakpoints widget is not disabled
def removeOldBreakpoints():
    test.log("Removing old breakpoints if there are any")
    try:
        breakPointTreeView = waitForObject("{type='Debugger::Internal::BreakWindow' visible='1' "
                                           "windowTitle='Breakpoints' name='Debugger.Docks.Break'}")
        model = breakPointTreeView.model()
        if model.rowCount()==0:
            test.log("No breakpoints found...")
        else:
            test.log("Found %d breakpoints - removing them" % model.rowCount())
            for row in range(model.rowCount()):
                currentIndex = model.index(row,0)
                rect = breakPointTreeView.visualRect(currentIndex)
                mouseClick(breakPointTreeView, rect.x+5, rect.y+5, 0, Qt.LeftButton)
                type(breakPointTreeView, "<Delete>")
    except LookupError:
        pass
    return test.compare(model.rowCount(), 0, "Check if all breakpoints have been removed.")

# function to do simple debugging of the current (configured) project
# param pressContinueCount defines how often it is expected to press
#       the 'Continue' button while debugging
# param expectedBPOrder holds a list of dicts where the dicts contain always
#       only 1 key:value pair - the key is the name of the file, the value is
#       line number where the debugger should stop
def doSimpleDebugging(currentConfigName, pressContinueCount=1, expectedBPOrder=[]):
    expectedLabelTexts = ['Stopped\.', 'Stopped at breakpoint \d+ \(\d+\) in thread \d+\.']<commit_msg>Squish: Fix possible access to None<commit_after>import re

def handleDebuggerWarnings(config):
    if "MSVC" in config:
        try:
            popup = waitForObject("{text?='<html><head/><body>*' type='QLabel' unnamed='1' visible='1' window=':Symbol Server_Utils::CheckableMessageBox'}", 10000)
            symServerNotConfiged = ("<html><head/><body><p>The debugger is not configured to use the public "
                                    "<a href=\"http://support.microsoft.com/kb/311503\">Microsoft Symbol Server</a>. "
                                    "This is recommended for retrieval of the symbols of the operating system libraries.</p>"
                                    "<p><i>Note:</i> A fast internet connection is required for this to work smoothly. "
                                    "Also, a delay might occur when connecting for the first time.</p>"
                                    "<p>Would you like to set it up?</p></br></body></html>")
            if popup.text == symServerNotConfiged:
                test.log("Creator warned about the debugger not being configured to use the public Microsoft Symbol Server.")
            else:
                test.warning("Creator showed an unexpected warning: " + str(popup.text))
            clickButton(waitForObject("{text='No' type='QPushButton' unnamed='1' visible='1' window=':Symbol Server_Utils::CheckableMessageBox'}", 10000))
        except LookupError:
            pass # No warning. Fine.
    else:
        if "Release" in config and platform.system() != "Darwin":
            message = waitForObject("{container=':Qt Creator.DebugModeWidget_QSplitter' name='qt_msgbox_label' type='QLabel' visible='1'}", 20000)
            test.compare(message.text, "This does not seem to be a \"Debug\" build.\nSetting breakpoints by file name and line number may fail.")
            clickButton("{container=':Qt Creator.DebugModeWidget_QSplitter' text='OK' type='QPushButton' unnamed='1' visible='1'}")

def takeDebuggerLog():
    invokeMenuItem("Window", "Views", "Debugger Log")
    debuggerLogWindow = waitForObject("{container=':DebugModeWidget.Debugger Log_QDockWidget' type='Debugger::Internal::CombinedPane' unnamed='1' visible='1'}", 20000)
    debuggerLog = str(debuggerLogWindow.plainText)
    mouseClick(debuggerLogWindow, 5, 5, 0, Qt.LeftButton)
    activateItem(waitForObjectItem(openContextMenuOnTextCursorPosition(debuggerLogWindow),
                                   "Clear Contents"))
    waitFor("str(debuggerLogWindow.plainText)==''", 5000)
    invokeMenuItem("Window", "Views", "Debugger Log")
    return debuggerLog

# function to set breakpoints for the current project
# on the given file,line pairs inside the given dict
# the lines are treated as regular expression
def setBreakpointsForCurrentProject(filesAndLines):
    # internal helper for setBreakpointsForCurrentProject
    # double clicks the treeElement inside the given navTree
    # TODO: merge with doubleClickFile() from tst_qml_editor & move to utils(?)
    def __doubleClickFile__(navTree, treeElement):
        waitForObjectItem(navTree, treeElement)
        fileNamePattern = re.compile(".*\.(?P<file>(.*\\\..*)?)$")
        fileName = fileNamePattern.search(treeElement).group("file").replace("\\.", ".")
        doubleClickItem(navTree, treeElement, 5, 5, 0, Qt.LeftButton)
        mainWindow = waitForObject(":Qt Creator_Core::Internal::MainWindow")
        waitFor('fileName in str(mainWindow.windowTitle)', 5000)
        return fileName

    switchViewTo(ViewConstants.DEBUG)
    removeOldBreakpoints()
    if not filesAndLines or not isinstance(filesAndLines, dict):
        test.fatal("This function only takes a non-empty dict.")
        return False
    navTree = waitForObject("{type='Utils::NavigationTreeView' unnamed='1' visible='1' "
                            "window=':Qt Creator_Core::Internal::MainWindow'}", 20000)
    for curFile,curLine in filesAndLines.iteritems():
        fName = __doubleClickFile__(navTree, curFile)
        editor = getEditorForFileSuffix(curFile)
        if not placeCursorToLine(editor, curLine, True):
            return False
        invokeMenuItem("Debug", "Toggle Breakpoint")
        test.log('Set breakpoint in %s' % fName, curLine)
    try:
        breakPointTreeView = waitForObject("{type='Debugger::Internal::BreakWindow' visible='1' "
                                           "windowTitle='Breakpoints' name='Debugger.Docks.Break'}")
        waitFor("breakPointTreeView.model().rowCount() == len(filesAndLines)", 2000)
    except:
        test.fatal("UI seems to have changed - check manually and fix this script.")
        return False
    test.compare(breakPointTreeView.model().rowCount(), len(filesAndLines),
                 'Expected %d set break points, found %d listed' %
                 (len(filesAndLines), breakPointTreeView.model().rowCount()))
    return True

# helper that removes all breakpoints - assumes that it's getting called
# being already on Debug view and Breakpoints widget is not disabled
def removeOldBreakpoints():
    test.log("Removing old breakpoints if there are any")
    try:
        breakPointTreeView = waitForObject("{type='Debugger::Internal::BreakWindow' visible='1' "
                                           "windowTitle='Breakpoints' name='Debugger.Docks.Break'}")
        model = breakPointTreeView.model()
        if model.rowCount()==0:
            test.log("No breakpoints found...")
        else:
            test.log("Found %d breakpoints - removing them" % model.rowCount())
            for row in range(model.rowCount()):
                currentIndex = model.index(row,0)
                rect = breakPointTreeView.visualRect(currentIndex)
                mouseClick(breakPointTreeView, rect.x+5, rect.y+5, 0, Qt.LeftButton)
                type(breakPointTreeView, "<Delete>")
    except:
        test.fatal("UI seems to have changed - check manually and fix this script.")
        return False
    return test.compare(model.rowCount(), 0, "Check if all breakpoints have been removed.")

# function to do simple debugging of the current (configured) project
# param pressContinueCount defines how often it is expected to press
#       the 'Continue' button while debugging
# param expectedBPOrder holds a list of dicts where the dicts contain always
#       only 1 key:value pair - the key is the name of the file, the value is
#       line number where the debugger should stop
def doSimpleDebugging(currentConfigName, pressContinueCount=1, expectedBPOrder=[]):
    expectedLabelTexts = ['Stopped\.', 'Stopped at breakpoint \d+ \(\d+\) in thread \d+\.']
{'fraction_non_alphanumeric': 0.11325245700245701, 'fraction_numerical': 0.01074938574938575, 'mean_word_length': 3.0677701436602125, 'pattern_counts': {'":': 4, '<': 45, '<?xml version=': 0, '>': 45, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 19, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3690642', 'n_tokens_mistral': 3548, 'n_tokens_neox': 3414, 'n_words': 984}