code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 2006-2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.HashMap; import javax.microedition.khronos.opengles.GL10; import android.graphics.Canvas; import android.graphics.Paint; import android.view.KeyEvent; class Message { private String mText; private long mExpirationTime; public Message(String text, long expirationTime) { this.mText = text; this.mExpirationTime = expirationTime; } public String getText() { return mText; } public long getExpirationTime() { return mExpirationTime; } } /** * A helper class to simplify writing an Activity that renders using * OpenGL ES. * * <p> A GLView object stores common elements of GL state and allows * them to be modified interactively. This is particularly useful for * determining the proper settings of parameters such as the view * frustum and light intensities during application development. * * <p> A GLView is not an actual View; instead, it is meant to be * called from within a View to perform event processing on behalf of the * actual View. * * <p> By passing key events to the GLView object from the View, * the application can automatically allow certain parameters to * be user-controlled from the keyboard. Key events may be passed as * shown below: * * <pre> * GLView mGlView = new GLView(); * * public boolean onKeyDown(int keyCode, KeyEvent event) { * // Hand the key to the GLView object first * if (mGlView.processKey(keyCode)) { * return; * } * * switch (keyCode) { * case KeyEvent.KEY_CODE_X: * // perform app processing * break; * * default: * super.onKeyDown(keyCode, event); * break; * } * } * </pre> * * <p> During drawing of a frame, the GLView object should be given the * opportunity to manage GL parameters as shown below: * * OpenGLContext mGLContext; // initialization not shown * int mNumTrianglesDrawn = 0; * * protected void onDraw(Canvas canvas) { * int w = getWidth(); * int h = getHeight(); * * float ratio = (float) w / h; * mGLView.setAspectRatio(ratio); * * GL10 gl = (GL10) mGLContext.getGL(); * mGLContext.waitNative(canvas, this); * * // Enable a light for the GLView to manipulate * gl.glEnable(GL10.GL_LIGHTING); * gl.glEnable(GL10.GL_LIGHT0); * * // Allow the GLView to set GL parameters * mGLView.setTextureParameters(gl); * mGLView.setProjection(gl); * mGLView.setView(gl); * mGLView.setLights(gl, GL10.GL_LIGHT0); * * // Draw some stuff (not shown) * mNumTrianglesDrawn += <num triangles just drawn>; * * // Wait for GL drawing to complete * mGLContext.waitGL(); * * // Inform the GLView of what was drawn, and ask it to display statistics * mGLView.setNumTriangles(mNumTrianglesDrawn); * mGLView.showMessages(canvas); * mGLView.showStatistics(canvas, w); * } * </pre> * * <p> At the end of each frame, following the call to * GLContext.waitGL, the showStatistics and showMessages methods * will cause additional information to be displayed. * * <p> To enter the interactive command mode, the 'tab' key must be * pressed twice in succession. A subsequent press of the 'tab' key * exits the interactive command mode. Entering a multi-letter code * sets the parameter to be modified. The 'newline' key erases the * current code, and the 'del' key deletes the last letter of * the code. The parameter value may be modified by pressing the * keypad left or up to decrement the value and right or down to * increment the value. The current value will be displayed as an * overlay above the GL rendered content. * * <p> The supported keyboard commands are as follows: * * <ul> * <li> h - display a list of commands * <li> fn - near frustum * <li> ff - far frustum * <li> tx - translate x * <li> ty - translate y * <li> tz - translate z * <li> z - zoom (frustum size) * <li> la - ambient light (all RGB channels) * <li> lar - ambient light red channel * <li> lag - ambient light green channel * <li> lab - ambient light blue channel * <li> ld - diffuse light (all RGB channels) * <li> ldr - diffuse light red channel * <li> ldg - diffuse light green channel * <li> ldb - diffuse light blue channel * <li> ls - specular light (all RGB channels) * <li> lsr - specular light red channel * <li> lsg - specular light green channel * <li> lsb - specular light blue channel * <li> lma - light model ambient (all RGB channels) * <li> lmar - light model ambient light red channel * <li> lmag - light model ambient green channel * <li> lmab - light model ambient blue channel * <li> tmin - texture min filter * <li> tmag - texture mag filter * <li> tper - texture perspective correction * </ul> * * {@hide} */ public class GLView { private static final int DEFAULT_DURATION_MILLIS = 1000; private static final int STATE_KEY = KeyEvent.KEYCODE_TAB; private static final int HAVE_NONE = 0; private static final int HAVE_ONE = 1; private static final int HAVE_TWO = 2; private static final float MESSAGE_Y_SPACING = 12.0f; private int mState = HAVE_NONE; private static final int NEAR_FRUSTUM = 0; private static final int FAR_FRUSTUM = 1; private static final int TRANSLATE_X = 2; private static final int TRANSLATE_Y = 3; private static final int TRANSLATE_Z = 4; private static final int ZOOM_EXPONENT = 5; private static final int AMBIENT_INTENSITY = 6; private static final int AMBIENT_RED = 7; private static final int AMBIENT_GREEN = 8; private static final int AMBIENT_BLUE = 9; private static final int DIFFUSE_INTENSITY = 10; private static final int DIFFUSE_RED = 11; private static final int DIFFUSE_GREEN = 12; private static final int DIFFUSE_BLUE = 13; private static final int SPECULAR_INTENSITY = 14; private static final int SPECULAR_RED = 15; private static final int SPECULAR_GREEN = 16; private static final int SPECULAR_BLUE = 17; private static final int LIGHT_MODEL_AMBIENT_INTENSITY = 18; private static final int LIGHT_MODEL_AMBIENT_RED = 19; private static final int LIGHT_MODEL_AMBIENT_GREEN = 20; private static final int LIGHT_MODEL_AMBIENT_BLUE = 21; private static final int TEXTURE_MIN_FILTER = 22; private static final int TEXTURE_MAG_FILTER = 23; private static final int TEXTURE_PERSPECTIVE_CORRECTION = 24; private static final String[] commands = { "fn", "ff", "tx", "ty", "tz", "z", "la", "lar", "lag", "lab", "ld", "ldr", "ldg", "ldb", "ls", "lsr", "lsg", "lsb", "lma", "lmar", "lmag", "lmab", "tmin", "tmag", "tper" }; private static final String[] labels = { "Near Frustum", "Far Frustum", "Translate X", "Translate Y", "Translate Z", "Zoom", "Ambient Intensity", "Ambient Red", "Ambient Green", "Ambient Blue", "Diffuse Intensity", "Diffuse Red", "Diffuse Green", "Diffuse Blue", "Specular Intenstity", "Specular Red", "Specular Green", "Specular Blue", "Light Model Ambient Intensity", "Light Model Ambient Red", "Light Model Ambient Green", "Light Model Ambient Blue", "Texture Min Filter", "Texture Mag Filter", "Texture Perspective Correction", }; private static final float[] defaults = { 5.0f, 100.0f, 0.0f, 0.0f, -50.0f, 0, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_FASTEST }; private static final float[] increments = { 0.01f, 0.5f, 0.125f, 0.125f, 0.125f, 1.0f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0, 0, 0 }; private float[] params = new float[commands.length]; private static final float mZoomScale = 0.109f; private static final float mZoomBase = 1.01f; private int mParam = -1; private float mIncr = 0; private Paint mPaint = new Paint(); private float mAspectRatio = 1.0f; private float mZoom; // private boolean mPerspectiveCorrection = false; // private int mTextureMinFilter = GL10.GL_NEAREST; // private int mTextureMagFilter = GL10.GL_NEAREST; // Counters for FPS calculation private boolean mDisplayFPS = false; private boolean mDisplayCounts = false; private int mFramesFPS = 10; private long[] mTimes = new long[mFramesFPS]; private int mTimesIdx = 0; private Map<String,Message> mMessages = new HashMap<String,Message>(); /** * Constructs a new GLView. */ public GLView() { mPaint.setColor(0xffffffff); reset(); } /** * Sets the aspect ratio (width/height) of the screen. * * @param aspectRatio the screen width divided by the screen height */ public void setAspectRatio(float aspectRatio) { this.mAspectRatio = aspectRatio; } /** * Sets the overall ambient light intensity. This intensity will * be used to modify the ambient light value for each of the red, * green, and blue channels passed to glLightfv(...GL_AMBIENT...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setAmbientIntensity(float intensity) { params[AMBIENT_INTENSITY] = intensity; } /** * Sets the light model ambient intensity. This intensity will be * used to modify the ambient light value for each of the red, * green, and blue channels passed to * glLightModelfv(GL_LIGHT_MODEL_AMBIENT...). The default value * is 0.125f. * * @param intensity a floating-point value controlling the overall * light model ambient intensity. */ public void setLightModelAmbientIntensity(float intensity) { params[LIGHT_MODEL_AMBIENT_INTENSITY] = intensity; } /** * Sets the ambient color for the red, green, and blue channels * that will be multiplied by the value of setAmbientIntensity and * passed to glLightfv(...GL_AMBIENT...). The default values are * {1, 1, 1}. * * @param ambient an arry of three floats containing ambient * red, green, and blue intensity values. */ public void setAmbientColor(float[] ambient) { params[AMBIENT_RED] = ambient[0]; params[AMBIENT_GREEN] = ambient[1]; params[AMBIENT_BLUE] = ambient[2]; } /** * Sets the overall diffuse light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_DIFFUSE...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setDiffuseIntensity(float intensity) { params[DIFFUSE_INTENSITY] = intensity; } /** * Sets the diffuse color for the red, green, and blue channels * that will be multiplied by the value of setDiffuseIntensity and * passed to glLightfv(...GL_DIFFUSE...). The default values are * {1, 1, 1}. * * @param diffuse an array of three floats containing diffuse * red, green, and blue intensity values. */ public void setDiffuseColor(float[] diffuse) { params[DIFFUSE_RED] = diffuse[0]; params[DIFFUSE_GREEN] = diffuse[1]; params[DIFFUSE_BLUE] = diffuse[2]; } /** * Sets the overall specular light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_SPECULAR...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setSpecularIntensity(float intensity) { params[SPECULAR_INTENSITY] = intensity; } /** * Sets the specular color for the red, green, and blue channels * that will be multiplied by the value of setSpecularIntensity and * passed to glLightfv(...GL_SPECULAR...). The default values are * {1, 1, 1}. * * @param specular an array of three floats containing specular * red, green, and blue intensity values. */ public void setSpecularColor(float[] specular) { params[SPECULAR_RED] = specular[0]; params[SPECULAR_GREEN] = specular[1]; params[SPECULAR_BLUE] = specular[2]; } /** * Returns the current X translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the X modelview translation as a float. */ public float getTranslateX() { return params[TRANSLATE_X]; } /** * Returns the current Y translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the Y modelview translation as a float. */ public float getTranslateY() { return params[TRANSLATE_Y]; } /** * Returns the current Z translation of the modelview * transformation as passed to glTranslatef. The default value is * -50.0f. * * @return the Z modelview translation as a float. */ public float getTranslateZ() { return params[TRANSLATE_Z]; } /** * Sets the position of the near frustum clipping plane as passed * to glFrustumf. The default value is 5.0f; * * @param nearFrustum the near frustum clipping plane distance as * a float. */ public void setNearFrustum(float nearFrustum) { params[NEAR_FRUSTUM] = nearFrustum; } /** * Sets the position of the far frustum clipping plane as passed * to glFrustumf. The default value is 100.0f; * * @param farFrustum the far frustum clipping plane distance as a * float. */ public void setFarFrustum(float farFrustum) { params[FAR_FRUSTUM] = farFrustum; } private void computeZoom() { mZoom = mZoomScale*(float)Math.pow(mZoomBase, -params[ZOOM_EXPONENT]); } /** * Resets all parameters to their default values. */ public void reset() { for (int i = 0; i < params.length; i++) { params[i] = defaults[i]; } computeZoom(); } private void removeExpiredMessages() { long now = System.currentTimeMillis(); List<String> toBeRemoved = new ArrayList<String>(); Iterator<String> keyIter = mMessages.keySet().iterator(); while (keyIter.hasNext()) { String key = keyIter.next(); Message msg = mMessages.get(key); if (msg.getExpirationTime() < now) { toBeRemoved.add(key); } } Iterator<String> tbrIter = toBeRemoved.iterator(); while (tbrIter.hasNext()) { String key = tbrIter.next(); mMessages.remove(key); } } /** * Displays the message overlay on the given Canvas. The * GLContext.waitGL method should be called prior to calling this * method. The interactive command display is drawn by this * method. * * @param canvas the Canvas on which messages are to appear. */ public void showMessages(Canvas canvas) { removeExpiredMessages(); float y = 10.0f; List<String> l = new ArrayList<String>(); l.addAll(mMessages.keySet()); Collections.sort(l); Iterator<String> iter = l.iterator(); while (iter.hasNext()) { String key = iter.next(); String text = mMessages.get(key).getText(); canvas.drawText(text, 10.0f, y, mPaint); y += MESSAGE_Y_SPACING; } } private int mTriangles; /** * Sets the number of triangles drawn in the previous frame for * display by the showStatistics method. The number of triangles * is not computed by GLView but must be supplied by the * calling Activity. * * @param triangles an Activity-supplied estimate of the number of * triangles drawn in the previous frame. */ public void setNumTriangles(int triangles) { this.mTriangles = triangles; } /** * Displays statistics on frames and triangles per second. The * GLContext.waitGL method should be called prior to calling this * method. * * @param canvas the Canvas on which statistics are to appear. * @param width the width of the Canvas. */ public void showStatistics(Canvas canvas, int width) { long endTime = mTimes[mTimesIdx] = System.currentTimeMillis(); mTimesIdx = (mTimesIdx + 1) % mFramesFPS; float th = mPaint.getTextSize(); if (mDisplayFPS) { // Use end time from mFramesFPS frames ago long startTime = mTimes[mTimesIdx]; String fps = "" + (1000.0f*mFramesFPS/(endTime - startTime)); // Normalize fps to XX.XX format if (fps.indexOf(".") == 1) { fps = " " + fps; } int len = fps.length(); if (len == 2) { fps += ".00"; } else if (len == 4) { fps += "0"; } else if (len > 5) { fps = fps.substring(0, 5); } canvas.drawText(fps + " fps", width - 60.0f, 10.0f, mPaint); } if (mDisplayCounts) { canvas.drawText(mTriangles + " triangles", width - 100.0f, 10.0f + th + 5, mPaint); } } private void addMessage(String key, String text, int durationMillis) { long expirationTime = System.currentTimeMillis() + durationMillis; mMessages.put(key, new Message(text, expirationTime)); } private void addMessage(String key, String text) { addMessage(key, text, DEFAULT_DURATION_MILLIS); } private void addMessage(String text) { addMessage(text, text, DEFAULT_DURATION_MILLIS); } private void clearMessages() { mMessages.clear(); } String command = ""; private void toggleFilter() { if (params[mParam] == GL10.GL_NEAREST) { params[mParam] = GL10.GL_LINEAR; } else { params[mParam] = GL10.GL_NEAREST; } addMessage(commands[mParam], "Texture " + (mParam == TEXTURE_MIN_FILTER ? "min" : "mag") + " filter = " + (params[mParam] == GL10.GL_NEAREST ? "nearest" : "linear")); } private void togglePerspectiveCorrection() { if (params[mParam] == GL10.GL_NICEST) { params[mParam] = GL10.GL_FASTEST; } else { params[mParam] = GL10.GL_NICEST; } addMessage(commands[mParam], "Texture perspective correction = " + (params[mParam] == GL10.GL_FASTEST ? "fastest" : "nicest")); } private String valueString() { if (mParam == TEXTURE_MIN_FILTER || mParam == TEXTURE_MAG_FILTER) { if (params[mParam] == GL10.GL_NEAREST) { return "nearest"; } if (params[mParam] == GL10.GL_LINEAR) { return "linear"; } } if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { if (params[mParam] == GL10.GL_FASTEST) { return "fastest"; } if (params[mParam] == GL10.GL_NICEST) { return "nicest"; } } return "" + params[mParam]; } /** * * @return true if the view */ public boolean hasMessages() { return mState == HAVE_TWO || mDisplayFPS || mDisplayCounts; } /** * Process a key stroke. The calling Activity should pass all * keys from its onKeyDown method to this method. If the key is * part of a GLView command, true is returned and the calling * Activity should ignore the key event. Otherwise, false is * returned and the calling Activity may process the key event * normally. * * @param keyCode the key code as passed to Activity.onKeyDown. * * @return true if the key is part of a GLView command sequence, * false otherwise. */ public boolean processKey(int keyCode) { // Pressing the state key twice enters the UI // Pressing it again exits the UI if ((keyCode == STATE_KEY) || (keyCode == KeyEvent.KEYCODE_SLASH) || (keyCode == KeyEvent.KEYCODE_PERIOD)) { mState = (mState + 1) % 3; if (mState == HAVE_NONE) { clearMessages(); } if (mState == HAVE_TWO) { clearMessages(); addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("aaab", "", Integer.MAX_VALUE); command = ""; } return true; } else { if (mState == HAVE_ONE) { mState = HAVE_NONE; return false; } } // If we're not in the UI, exit without handling the key if (mState != HAVE_TWO) { return false; } if (keyCode == KeyEvent.KEYCODE_ENTER) { command = ""; } else if (keyCode == KeyEvent.KEYCODE_DEL) { if (command.length() > 0) { command = command.substring(0, command.length() - 1); } } else if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) { command += "" + (char)(keyCode - KeyEvent.KEYCODE_A + 'a'); } addMessage("aaaa", "GL " + command, Integer.MAX_VALUE); if (command.equals("h")) { addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("h - help"); addMessage("fn/ff - frustum near/far clip Z"); addMessage("la/lar/lag/lab - abmient intensity/r/g/b"); addMessage("ld/ldr/ldg/ldb - diffuse intensity/r/g/b"); addMessage("ls/lsr/lsg/lsb - specular intensity/r/g/b"); addMessage("s - toggle statistics display"); addMessage("tmin/tmag - texture min/mag filter"); addMessage("tpersp - texture perspective correction"); addMessage("tx/ty/tz - view translate x/y/z"); addMessage("z - zoom"); command = ""; return true; } else if (command.equals("s")) { mDisplayCounts = !mDisplayCounts; mDisplayFPS = !mDisplayFPS; command = ""; return true; } mParam = -1; for (int i = 0; i < commands.length; i++) { if (command.equals(commands[i])) { mParam = i; mIncr = increments[i]; } } if (mParam == -1) { return true; } boolean addMessage = true; // Increment or decrement if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (mParam == ZOOM_EXPONENT) { params[mParam] += mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] += mIncr; } } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { if (mParam == ZOOM_EXPONENT) { params[mParam] -= mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] -= mIncr; } } if (addMessage) { addMessage(commands[mParam], labels[mParam] + ": " + valueString()); } return true; } /** * Zoom in by a given number of steps. A negative value of steps * zooms out. Each step zooms in by 1%. * * @param steps the number of steps to zoom by. */ public void zoom(int steps) { params[ZOOM_EXPONENT] += steps; computeZoom(); } /** * Set the projection matrix using glFrustumf. The left and right * clipping planes are set at -+(aspectRatio*zoom), the bottom and * top clipping planes are set at -+zoom, and the near and far * clipping planes are set to the values set by setNearFrustum and * setFarFrustum or interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the projection matrix</li> * </ul> * * @param gl a GL10 instance whose projection matrix is to be modified. */ public void setProjection(GL10 gl) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); if (mAspectRatio >= 1.0f) { gl.glFrustumf(-mAspectRatio*mZoom, mAspectRatio*mZoom, -mZoom, mZoom, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } else { gl.glFrustumf(-mZoom, mZoom, -mZoom / mAspectRatio, mZoom / mAspectRatio, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } } /** * Set the modelview matrix using glLoadIdentity and glTranslatef. * The translation values are set interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the modelview matrix</li> * </ul> * * @param gl a GL10 instance whose modelview matrix is to be modified. */ public void setView(GL10 gl) { gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); // Move the viewpoint backwards gl.glTranslatef(params[TRANSLATE_X], params[TRANSLATE_Y], params[TRANSLATE_Z]); } /** * Sets texture parameters. * * <p> GL side effects: * <ul> * <li>sets the GL_PERSPECTIVE_CORRECTION_HINT</li> * <li>sets the GL_TEXTURE_MIN_FILTER texture parameter</li> * <li>sets the GL_TEXTURE_MAX_FILTER texture parameter</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setTextureParameters(GL10 gl) { gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, (int)params[TEXTURE_PERSPECTIVE_CORRECTION]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, params[TEXTURE_MIN_FILTER]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, params[TEXTURE_MAG_FILTER]); } /** * Sets the lighting parameters for the given light. * * <p> GL side effects: * <ul> * <li>sets the GL_LIGHT_MODEL_AMBIENT intensities * <li>sets the GL_AMBIENT intensities for the given light</li> * <li>sets the GL_DIFFUSE intensities for the given light</li> * <li>sets the GL_SPECULAR intensities for the given light</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setLights(GL10 gl, int lightNum) { float[] light = new float[4]; light[3] = 1.0f; float lmi = params[LIGHT_MODEL_AMBIENT_INTENSITY]; light[0] = params[LIGHT_MODEL_AMBIENT_RED]*lmi; light[1] = params[LIGHT_MODEL_AMBIENT_GREEN]*lmi; light[2] = params[LIGHT_MODEL_AMBIENT_BLUE]*lmi; gl.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, light, 0); float ai = params[AMBIENT_INTENSITY]; light[0] = params[AMBIENT_RED]*ai; light[1] = params[AMBIENT_GREEN]*ai; light[2] = params[AMBIENT_BLUE]*ai; gl.glLightfv(lightNum, GL10.GL_AMBIENT, light, 0); float di = params[DIFFUSE_INTENSITY]; light[0] = params[DIFFUSE_RED]*di; light[1] = params[DIFFUSE_GREEN]*di; light[2] = params[DIFFUSE_BLUE]*di; gl.glLightfv(lightNum, GL10.GL_DIFFUSE, light, 0); float si = params[SPECULAR_INTENSITY]; light[0] = params[SPECULAR_RED]*si; light[1] = params[SPECULAR_GREEN]*si; light[2] = params[SPECULAR_BLUE]*si; gl.glLightfv(lightNum, GL10.GL_SPECULAR, light, 0); } }
zzsheng0924-7way
AndroidGlobalTime/src/com/android/globaltime/GLView.java
Java
asf20
30,586
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; public class LatLongSphere extends Sphere { public LatLongSphere(float centerX, float centerY, float centerZ, float radius, int lats, int longs, float minLongitude, float maxLongitude, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors, boolean flatten) { super(emitTextureCoordinates, emitNormals, emitColors); int tris = 2 * (lats - 1) * (longs - 1); int[] vertices = new int[3 * lats * longs]; int[] texcoords = new int[2 * lats * longs]; int[] colors = new int[4 * lats * longs]; int[] normals = new int[3 * lats * longs]; short[] indices = new short[3 * tris]; int vidx = 0; int tidx = 0; int nidx = 0; int cidx = 0; int iidx = 0; minLongitude *= DEGREES_TO_RADIANS; maxLongitude *= DEGREES_TO_RADIANS; for (int i = 0; i < longs; i++) { float fi = (float) i / (longs - 1); // theta is the longitude float theta = (maxLongitude - minLongitude) * (1.0f - fi) + minLongitude; float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); for (int j = 0; j < lats; j++) { float fj = (float) j / (lats - 1); // phi is the latitude float phi = PI * fj; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; if (flatten) { // Place vertices onto a flat projection vertices[vidx++] = toFixed(2.0f * fi - 1.0f); vertices[vidx++] = toFixed(0.5f - fj); vertices[vidx++] = toFixed(0.0f); } else { // Place vertices onto the surface of a sphere // with the given center and radius vertices[vidx++] = toFixed(x * radius + centerX); vertices[vidx++] = toFixed(y * radius + centerY); vertices[vidx++] = toFixed(z * radius + centerZ); } if (emitTextureCoordinates) { texcoords[tidx++] = toFixed(1.0f - (theta / (TWO_PI))); texcoords[tidx++] = toFixed(fj); } if (emitNormals) { float norm = 1.0f / Shape.length(x, y, z); normals[nidx++] = toFixed(x * norm); normals[nidx++] = toFixed(y * norm); normals[nidx++] = toFixed(z * norm); } // 0 == black, 65536 == white if (emitColors) { colors[cidx++] = (i % 2) * 65536; colors[cidx++] = 0; colors[cidx++] = (j % 2) * 65536; colors[cidx++] = 65536; } } } for (int i = 0; i < longs - 1; i++) { for (int j = 0; j < lats - 1; j++) { int base = i * lats + j; // Ensure both triangles have the same final vertex // since this vertex carries the color for flat // shading indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + 1); indices[iidx++] = (short) (base + lats + 1); indices[iidx++] = (short) (base + lats); indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + lats + 1); } } allocateBuffers(vertices, texcoords, normals, colors, indices); } }
zzsheng0924-7way
AndroidGlobalTime/src/com/android/globaltime/LatLongSphere.java
Java
asf20
4,464
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.nio.ByteBuffer; public class Texture { private ByteBuffer data; private int width, height; public Texture(ByteBuffer data, int width, int height) { this.data = data; this.width = width; this.height = height; } public ByteBuffer getData() { return data; } public int getWidth() { return width; } public int getHeight() { return height; } }
zzsheng0924-7way
AndroidGlobalTime/src/com/android/globaltime/Texture.java
Java
asf20
1,079
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @fileoverview Bookmark bubble library. This is meant to be included in the * main JavaScript binary of a mobile web application. * * Supported browsers: iPhone / iPod / iPad Safari 3.0+ */ var google = google || {}; google.bookmarkbubble = google.bookmarkbubble || {}; /** * Binds a context object to the function. * @param {Function} fn The function to bind to. * @param {Object} context The "this" object to use when the function is run. * @return {Function} A partially-applied form of fn. */ google.bind = function(fn, context) { return function() { return fn.apply(context, arguments); }; }; /** * Function used to define an abstract method in a base class. If a subclass * fails to override the abstract method, then an error will be thrown whenever * that method is invoked. */ google.abstractMethod = function() { throw Error('Unimplemented abstract method.'); }; /** * The bubble constructor. Instantiating an object does not cause anything to * be rendered yet, so if necessary you can set instance properties before * showing the bubble. * @constructor */ google.bookmarkbubble.Bubble = function() { /** * Handler for the scroll event. Keep a reference to it here, so it can be * unregistered when the bubble is destroyed. * @type {function()} * @private */ this.boundScrollHandler_ = google.bind(this.setPosition, this); /** * The bubble element. * @type {Element} * @private */ this.element_ = null; /** * Whether the bubble has been destroyed. * @type {boolean} * @private */ this.hasBeenDestroyed_ = false; }; /** * Shows the bubble if allowed. It is not allowed if: * - The browser is not Mobile Safari, or * - The user has dismissed it too often already, or * - The hash parameter is present in the location hash, or * - The application is in fullscreen mode, which means it was already loaded * from a homescreen bookmark. * @return {boolean} True if the bubble is being shown, false if it is not * allowed to show for one of the aforementioned reasons. */ google.bookmarkbubble.Bubble.prototype.showIfAllowed = function() { if (!this.isAllowedToShow_()) { return false; } this.show_(); return true; }; /** * Shows the bubble if allowed after loading the icon image. This method creates * an image element to load the image into the browser's cache before showing * the bubble to ensure that the image isn't blank. Use this instead of * showIfAllowed if the image url is http and cacheable. * This hack is necessary because Mobile Safari does not properly render * image elements with border-radius CSS. * @param {function()} opt_callback Closure to be called if and when the bubble * actually shows. * @return {boolean} True if the bubble is allowed to show. */ google.bookmarkbubble.Bubble.prototype.showIfAllowedWhenLoaded = function(opt_callback) { if (!this.isAllowedToShow_()) { return false; } var self = this; // Attach to self to avoid garbage collection. var img = self.loadImg_ = document.createElement('img'); img.src = self.getIconUrl_(); img.onload = function() { if (img.complete) { delete self.loadImg_; img.onload = null; // Break the circular reference. self.show_(); opt_callback && opt_callback(); } }; img.onload(); return true; }; /** * Sets the parameter in the location hash. As it is * unpredictable what hash scheme is to be used, this method must be * implemented by the host application. * * This gets called automatically when the bubble is shown. The idea is that if * the user then creates a bookmark, we can later recognize on application * startup whether it was from a bookmark suggested with this bubble. * * NOTE: Using a hash parameter to track whether the bubble has been shown * conflicts with the navigation system in jQuery Mobile. If you are using that * library, you should implement this function to track the bubble's status in * a different way, e.g. using window.localStorage in HTML5. */ google.bookmarkbubble.Bubble.prototype.setHashParameter = google.abstractMethod; /** * Whether the parameter is present in the location hash. As it is * unpredictable what hash scheme is to be used, this method must be * implemented by the host application. * * Call this method during application startup if you want to log whether the * application was loaded from a bookmark with the bookmark bubble promotion * parameter in it. * * @return {boolean} Whether the bookmark bubble parameter is present in the * location hash. */ google.bookmarkbubble.Bubble.prototype.hasHashParameter = google.abstractMethod; /** * The number of times the user must dismiss the bubble before we stop showing * it. This is a public property and can be changed by the host application if * necessary. * @type {number} */ google.bookmarkbubble.Bubble.prototype.NUMBER_OF_TIMES_TO_DISMISS = 2; /** * Time in milliseconds. If the user does not dismiss the bubble, it will auto * destruct after this amount of time. * @type {number} */ google.bookmarkbubble.Bubble.prototype.TIME_UNTIL_AUTO_DESTRUCT = 15000; /** * The prefix for keys in local storage. This is a public property and can be * changed by the host application if necessary. * @type {string} */ google.bookmarkbubble.Bubble.prototype.LOCAL_STORAGE_PREFIX = 'BOOKMARK_'; /** * The key name for the dismissed state. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.DISMISSED_ = 'DISMISSED_COUNT'; /** * The arrow image in base64 data url format. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.IMAGE_ARROW_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAATCAMAAABSrFY3AAABKVBMVEUAAAD///8AAAAAAAAAAAAAAAAAAADf398AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD09PQAAAAAAAAAAAC9vb0AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD19fUAAAAAAAAAAAAAAADq6uoAAAAAAAAAAAC8vLzU1NTT09MAAADg4OAAAADs7OwAAAAAAAAAAAD///+cueenwerA0vC1y+3a5fb5+/3t8vr4+v3w9PuwyOy3zO3h6vfh6vjq8Pqkv+mat+fE1fHB0/Cduuifu+iuxuuivemrxOvC1PDz9vzJ2fKpwuqmwOrb5vapw+q/0vDf6ffK2vLN3PPprJISAAAAQHRSTlMAAAEGExES7FM+JhUoQSxIRwMbNfkJUgXXBE4kDQIMHSA0Tw4xIToeTSc4Chz4OyIjPfI3QD/X5OZR6zzwLSUPrm1y3gAAAQZJREFUeF5lzsVyw0AURNE3IMsgmZmZgszQZoeZOf//EYlG5Yrhbs+im4Dj7slM5wBJ4OJ+undAUr68gK/Hyb6Bcp5yBR/w8jreNeAr5Eg2XE7g6e2/0z6cGw1JQhpmHP3u5aiPPnTTkIK48Hj9Op7bD3btAXTfgUdwYjwSDCVXMbizO0O4uDY/x4kYC5SWFnfC6N1a9RCO7i2XEmQJj2mHK1Hgp9Vq3QBRl9shuBLGhcNtHexcdQCnDUoUGetxDD+H2DQNG2xh6uAWgG2/17o1EmLqYH0Xej0UjHAaFxZIV6rJ/WK1kg7QZH8HU02zmdJinKZJaDV3TVMjM5Q9yiqYpUwiMwa/1apDXTNESjsAAAAASUVORK5CYII='; /** * The close image in base64 data url format. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.IMAGE_CLOSE_DATA_URL_ = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAALVBMVEXM3fm+1Pfb5/rF2fjw9f23z/aavPOhwfTp8PyTt/L3+v7T4vqMs/K7zP////+qRWzhAAAAXElEQVQIW2O4CwUM996BwVskxtOqd++2rwMyPI+ve31GD8h4Madqz2mwms5jZ/aBGS/mHIDoen3m+DowY8/hOVUgxusz+zqPg7SvPA1UxQfSvu/du0YUK2AMmDMA5H1qhVX33T8AAAAASUVORK5CYII='; /** * The link used to locate the application's home screen icon to display inside * the bubble. The default link used here is for an iPhone home screen icon * without gloss. If your application uses a glossy icon, change this to * 'apple-touch-icon'. * @type {string} * @private */ google.bookmarkbubble.Bubble.prototype.REL_ICON_ = 'apple-touch-icon-precomposed'; /** * Regular expression for detecting an iPhone or iPod or iPad. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.MOBILE_SAFARI_USERAGENT_REGEX_ = /iPhone|iPod|iPad/; /** * Regular expression for detecting an iPad. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.IPAD_USERAGENT_REGEX_ = /iPad/; /** * Regular expression for extracting the iOS version. Only matches 2.0 and up. * @type {!RegExp} * @private */ google.bookmarkbubble.Bubble.prototype.IOS_VERSION_USERAGENT_REGEX_ = /OS (\d)_(\d)(?:_(\d))?/; /** * Determines whether the bubble should be shown or not. * @return {boolean} Whether the bubble should be shown or not. * @private */ google.bookmarkbubble.Bubble.prototype.isAllowedToShow_ = function() { return this.isMobileSafari_() && !this.hasBeenDismissedTooManyTimes_() && !this.isFullscreen_() && !this.hasHashParameter(); }; /** * Builds and shows the bubble. * @private */ google.bookmarkbubble.Bubble.prototype.show_ = function() { this.element_ = this.build_(); document.body.appendChild(this.element_); this.element_.style.WebkitTransform = 'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)'; this.setHashParameter(); window.setTimeout(this.boundScrollHandler_, 1); window.addEventListener('scroll', this.boundScrollHandler_, false); // If the user does not dismiss the bubble, slide out and destroy it after // some time. window.setTimeout(google.bind(this.autoDestruct_, this), this.TIME_UNTIL_AUTO_DESTRUCT); }; /** * Destroys the bubble by removing its DOM nodes from the document. */ google.bookmarkbubble.Bubble.prototype.destroy = function() { if (this.hasBeenDestroyed_) { return; } window.removeEventListener('scroll', this.boundScrollHandler_, false); if (this.element_ && this.element_.parentNode == document.body) { document.body.removeChild(this.element_); this.element_ = null; } this.hasBeenDestroyed_ = true; }; /** * Remember that the user has dismissed the bubble once more. * @private */ google.bookmarkbubble.Bubble.prototype.rememberDismissal_ = function() { if (window.localStorage) { try { var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_; var value = Number(window.localStorage[key]) || 0; window.localStorage[key] = String(value + 1); } catch (ex) { // Looks like we've hit the storage size limit. Currently we have no // fallback for this scenario, but we could use cookie storage instead. // This would increase the code bloat though. } } }; /** * Whether the user has dismissed the bubble often enough that we will not * show it again. * @return {boolean} Whether the user has dismissed the bubble often enough * that we will not show it again. * @private */ google.bookmarkbubble.Bubble.prototype.hasBeenDismissedTooManyTimes_ = function() { if (!window.localStorage) { // If we can not use localStorage to remember how many times the user has // dismissed the bubble, assume he has dismissed it. Otherwise we might end // up showing it every time the host application loads, into eternity. return true; } try { var key = this.LOCAL_STORAGE_PREFIX + this.DISMISSED_; // If the key has never been set, localStorage yields undefined, which // Number() turns into NaN. In that case we'll fall back to zero for // clarity's sake. var value = Number(window.localStorage[key]) || 0; return value >= this.NUMBER_OF_TIMES_TO_DISMISS; } catch (ex) { // If we got here, something is wrong with the localStorage. Make the same // assumption as when it does not exist at all. Exceptions should only // occur when setting a value (due to storage limitations) but let's be // extra careful. return true; } }; /** * Whether the application is running in fullscreen mode. * @return {boolean} Whether the application is running in fullscreen mode. * @private */ google.bookmarkbubble.Bubble.prototype.isFullscreen_ = function() { return !!window.navigator.standalone; }; /** * Whether the application is running inside Mobile Safari. * @return {boolean} True if the current user agent looks like Mobile Safari. * @private */ google.bookmarkbubble.Bubble.prototype.isMobileSafari_ = function() { return this.MOBILE_SAFARI_USERAGENT_REGEX_.test(window.navigator.userAgent); }; /** * Whether the application is running on an iPad. * @return {boolean} True if the current user agent looks like an iPad. * @private */ google.bookmarkbubble.Bubble.prototype.isIpad_ = function() { return this.IPAD_USERAGENT_REGEX_.test(window.navigator.userAgent); }; /** * Creates a version number from 4 integer pieces between 0 and 127 (inclusive). * @param {*=} opt_a The major version. * @param {*=} opt_b The minor version. * @param {*=} opt_c The revision number. * @param {*=} opt_d The build number. * @return {number} A representation of the version. * @private */ google.bookmarkbubble.Bubble.prototype.getVersion_ = function(opt_a, opt_b, opt_c, opt_d) { // We want to allow implicit conversion of any type to number while avoiding // compiler warnings about the type. return /** @type {number} */ (opt_a) << 21 | /** @type {number} */ (opt_b) << 14 | /** @type {number} */ (opt_c) << 7 | /** @type {number} */ (opt_d); }; /** * Gets the iOS version of the device. Only works for 2.0+. * @return {number} The iOS version. * @private */ google.bookmarkbubble.Bubble.prototype.getIosVersion_ = function() { var groups = this.IOS_VERSION_USERAGENT_REGEX_.exec( window.navigator.userAgent) || []; groups.shift(); return this.getVersion_.apply(this, groups); }; /** * Positions the bubble at the bottom of the viewport using an animated * transition. */ google.bookmarkbubble.Bubble.prototype.setPosition = function() { this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-out'; this.element_.style.WebkitTransform = 'translate3d(0,' + this.getVisibleYPosition_() + 'px,0)'; }; /** * Destroys the bubble by removing its DOM nodes from the document, and * remembers that it was dismissed. * @private */ google.bookmarkbubble.Bubble.prototype.closeClickHandler_ = function() { this.destroy(); this.rememberDismissal_(); }; /** * Gets called after a while if the user ignores the bubble. * @private */ google.bookmarkbubble.Bubble.prototype.autoDestruct_ = function() { if (this.hasBeenDestroyed_) { return; } this.element_.style.WebkitTransition = '-webkit-transform 0.7s ease-in'; this.element_.style.WebkitTransform = 'translate3d(0,' + this.getHiddenYPosition_() + 'px,0)'; window.setTimeout(google.bind(this.destroy, this), 700); }; /** * Gets the y offset used to show the bubble (i.e., position it on-screen). * @return {number} The y offset. * @private */ google.bookmarkbubble.Bubble.prototype.getVisibleYPosition_ = function() { return this.isIpad_() ? window.pageYOffset + 17 : window.pageYOffset - this.element_.offsetHeight + window.innerHeight - 17; }; /** * Gets the y offset used to hide the bubble (i.e., position it off-screen). * @return {number} The y offset. * @private */ google.bookmarkbubble.Bubble.prototype.getHiddenYPosition_ = function() { return this.isIpad_() ? window.pageYOffset - this.element_.offsetHeight : window.pageYOffset + window.innerHeight; }; /** * The url of the app's bookmark icon. * @type {string|undefined} * @private */ google.bookmarkbubble.Bubble.prototype.iconUrl_; /** * Scrapes the document for a link element that specifies an Apple favicon and * returns the icon url. Returns an empty data url if nothing can be found. * @return {string} A url string. * @private */ google.bookmarkbubble.Bubble.prototype.getIconUrl_ = function() { if (!this.iconUrl_) { var link = this.getLink(this.REL_ICON_); if (!link || !(this.iconUrl_ = link.href)) { this.iconUrl_ = 'data:image/png;base64,'; } } return this.iconUrl_; }; /** * Gets the requested link tag if it exists. * @param {string} rel The rel attribute of the link tag to get. * @return {Element} The requested link tag or null. */ google.bookmarkbubble.Bubble.prototype.getLink = function(rel) { rel = rel.toLowerCase(); var links = document.getElementsByTagName('link'); for (var i = 0; i < links.length; ++i) { var currLink = /** @type {Element} */ (links[i]); if (currLink.getAttribute('rel').toLowerCase() == rel) { return currLink; } } return null; }; /** * Creates the bubble and appends it to the document. * @return {Element} The bubble element. * @private */ google.bookmarkbubble.Bubble.prototype.build_ = function() { var bubble = document.createElement('div'); var isIpad = this.isIpad_(); bubble.style.position = 'absolute'; bubble.style.zIndex = 1000; bubble.style.width = '100%'; bubble.style.left = '0'; bubble.style.top = '0'; var bubbleInner = document.createElement('div'); bubbleInner.style.position = 'relative'; bubbleInner.style.width = '214px'; bubbleInner.style.margin = isIpad ? '0 0 0 82px' : '0 auto'; bubbleInner.style.border = '2px solid #fff'; bubbleInner.style.padding = '20px 20px 20px 10px'; bubbleInner.style.WebkitBorderRadius = '8px'; bubbleInner.style.WebkitBoxShadow = '0 0 8px rgba(0, 0, 0, 0.7)'; bubbleInner.style.WebkitBackgroundSize = '100% 8px'; bubbleInner.style.backgroundColor = '#b0c8ec'; bubbleInner.style.background = '#cddcf3 -webkit-gradient(linear, ' + 'left bottom, left top, ' + isIpad ? 'from(#cddcf3), to(#b3caed)) no-repeat top' : 'from(#b3caed), to(#cddcf3)) no-repeat bottom'; bubbleInner.style.font = '13px/17px sans-serif'; bubble.appendChild(bubbleInner); // The "Add to Home Screen" text is intended to be the exact same text // that is displayed in the menu of Mobile Safari. if (this.getIosVersion_() >= this.getVersion_(4, 2)) { bubbleInner.innerHTML = 'Install this web app on your phone: ' + 'tap on the arrow and then <b>\'Add to Home Screen\'</b>'; } else { bubbleInner.innerHTML = 'Install this web app on your phone: ' + 'tap <b style="font-size:15px">+</b> and then ' + '<b>\'Add to Home Screen\'</b>'; } var icon = document.createElement('div'); icon.style['float'] = 'left'; icon.style.width = '55px'; icon.style.height = '55px'; icon.style.margin = '-2px 7px 3px 5px'; icon.style.background = '#fff url(' + this.getIconUrl_() + ') no-repeat -1px -1px'; icon.style.WebkitBackgroundSize = '57px'; icon.style.WebkitBorderRadius = '10px'; icon.style.WebkitBoxShadow = '0 2px 5px rgba(0, 0, 0, 0.4)'; bubbleInner.insertBefore(icon, bubbleInner.firstChild); var arrow = document.createElement('div'); arrow.style.backgroundImage = 'url(' + this.IMAGE_ARROW_DATA_URL_ + ')'; arrow.style.width = '25px'; arrow.style.height = '19px'; arrow.style.position = 'absolute'; arrow.style.left = '111px'; if (isIpad) { arrow.style.WebkitTransform = 'rotate(180deg)'; arrow.style.top = '-19px'; } else { arrow.style.bottom = '-19px'; } bubbleInner.appendChild(arrow); var close = document.createElement('a'); close.onclick = google.bind(this.closeClickHandler_, this); close.style.position = 'absolute'; close.style.display = 'block'; close.style.top = '-3px'; close.style.right = '-3px'; close.style.width = '16px'; close.style.height = '16px'; close.style.border = '10px solid transparent'; close.style.background = 'url(' + this.IMAGE_CLOSE_DATA_URL_ + ') no-repeat'; bubbleInner.appendChild(close); return bubble; };
zziuni-mobile-bookmark-bubble
bookmark_bubble.js
JavaScript
asf20
19,874
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <!-- Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <html> <head> <title>Sample</title> <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0" /> <meta name="apple-mobile-web-app-capable" content="yes" /> <link rel="apple-touch-icon-precomposed" href="../images/icon_calendar.png" /> <script type="text/javascript" src="../bookmark_bubble.js"></script> <script type="text/javascript" src="example.js"></script> </head> <body style="height: 3000px;"> <p>The bookmark bubble will show after a second, if:</p> <ul> <li>It has not been previously dismissed too often</li> <li>The application is not running in full screen mode</li> <li>The bookmark bubble hash token is not present</li> </ul> <p>Supported browsers:</p> <ul> <li>iPhone / iPod / iPad Mobile Safari 3.0+</li> </ul> </body> </html>
zziuni-mobile-bookmark-bubble
example/example.html
HTML
asf20
1,540
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** @fileoverview Example of how to use the bookmark bubble. */ window.addEventListener('load', function() { window.setTimeout(function() { var bubble = new google.bookmarkbubble.Bubble(); var parameter = 'bmb=1'; bubble.hasHashParameter = function() { return window.location.hash.indexOf(parameter) != -1; }; bubble.setHashParameter = function() { if (!this.hasHashParameter()) { window.location.hash += parameter; } }; bubble.getViewportHeight = function() { window.console.log('Example of how to override getViewportHeight.'); return window.innerHeight; }; bubble.getViewportScrollY = function() { window.console.log('Example of how to override getViewportScrollY.'); return window.pageYOffset; }; bubble.registerScrollHandler = function(handler) { window.console.log('Example of how to override registerScrollHandler.'); window.addEventListener('scroll', handler, false); }; bubble.deregisterScrollHandler = function(handler) { window.console.log('Example of how to override deregisterScrollHandler.'); window.removeEventListener('scroll', handler, false); }; bubble.showIfAllowed(); }, 1000); }, false);
zziuni-mobile-bookmark-bubble
example/example.js
JavaScript
asf20
1,836
#!/bin/bash # Copyright 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Generates base64 versions of images so they can be inlined using the 'data:' # URI scheme. declare -ra IMAGE_FILES=( close.png arrow.png ) for image in ${IMAGE_FILES[@]}; do OUT="$image.base64" cat "$image" \ | uuencode -m ignore-this \ | grep -v begin-base64 \ | grep -v "====" \ | xargs echo \ | sed -e 's/ //g' \ | xargs echo -n \ > $OUT ls -l $OUT done
zziuni-mobile-bookmark-bubble
images/generate_base64_images
Shell
asf20
999
using System; using System.Globalization; using Compiler.Helpers.SemanticAnalyze; namespace Compiler.Helpers { internal static class EnumExtensions { public static string GetParamString(this Enum @enum) { var type = @enum.GetType(); #pragma warning disable 612,618 var fieldInfo = type.GetField(@enum.ToString(CultureInfo.InvariantCulture)); #pragma warning restore 612,618 var attributes = fieldInfo.GetCustomAttributes(typeof(StringContentAttribute), false) as StringContentAttribute[]; if (attributes != null && attributes.Length > 0) { return attributes[0].Content; } #pragma warning disable 612,618 return @enum.ToString(CultureInfo.InvariantCulture); #pragma warning restore 612,618 } } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/EnumExtensions.cs
C#
asf20
873
using System.Collections.Generic; namespace Compiler.Helpers.SemanticAnalyze { public class Function : UniqueObject { public Function() {} public Function(string id, LanguageTypes type) :base(id) { Type = type; } public Function(string id, LanguageTypes type, IEnumerable<Variable> arguments) :this(id, type) { Arguments = arguments; } public LanguageTypes Type { get; private set; } public IEnumerable<Variable> Arguments { get; private set; } } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/SemanticAnalyze/Function.cs
C#
asf20
632
namespace Compiler.Helpers.SemanticAnalyze { public enum LanguageTypes { [StringContent("void")] Void, [StringContent("bool")] Bool, [StringContent("int")] Int, [StringContent("string")] String, [StringContent("list")] List } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/SemanticAnalyze/LanguageTypes.cs
C#
asf20
337
namespace Compiler.Helpers.SemanticAnalyze { public abstract class UniqueObject { protected UniqueObject() {} protected UniqueObject(string id) { Id = id; } public string Id { get; set; } public override bool Equals(object obj) { if (obj == null) { return false; } var other = obj as UniqueObject; if (other == null) { return false; } return Id == other.Id; } public bool Equals(UniqueObject other) { if ((object)other == null) { return false; } return Id == other.Id; } public override int GetHashCode() { return Id.GetHashCode(); } public static bool operator == (UniqueObject firstOne, UniqueObject secondOne) { if (ReferenceEquals(firstOne, secondOne)) { return true; } if ((object)firstOne == null || (object)secondOne == null) { return false; } return firstOne.Id == secondOne.Id; } public static bool operator != (UniqueObject firstOne, UniqueObject secondOne) { return !(firstOne == secondOne); } } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/SemanticAnalyze/UniqueObject.cs
C#
asf20
1,520
using System.Collections; using System.Collections.Generic; using System.Linq; namespace Compiler.Helpers.SemanticAnalyze { public class ReferenceContainer<T> : IEnumerable<T> where T : UniqueObject { protected readonly IList<T> Elements = new List<T>(); public ReferenceContainer() {} public ReferenceContainer(IEnumerable<T> elements) : this() { foreach (var element in elements) { Elements.Add(element); } } public T Resolve(string id) { return Elements.FirstOrDefault(element => element.Id == id); } public T Resolve(T uniqueObject) { return Elements.FirstOrDefault(element => element == uniqueObject); } public void Add(T uniqueObject) { Elements.Add(uniqueObject); } public void Remove(T uniqueObject) { var removedElement = Elements.FirstOrDefault(element => element == uniqueObject); if (removedElement == null) { return; } Elements.Remove(removedElement); } public void Remove(string id) { var removedElement = Elements.FirstOrDefault(element => element.Id == id); if (removedElement == null) { return; } Elements.Remove(removedElement); } #region Implementation of IEnumerable public IEnumerator<T> GetEnumerator() { return Elements.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/SemanticAnalyze/ReferenceContainer.cs
C#
asf20
1,847
namespace Compiler.Helpers.SemanticAnalyze { public class Variable : UniqueObject { public Variable() {} public Variable(string id, LanguageTypes type) :base(id) { Type = type; } public Variable(string id, LanguageTypes type, dynamic value) : this(id, type) { Value = value; } public LanguageTypes Type { get; private set; } public dynamic Value { get; set; } } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/SemanticAnalyze/Variable.cs
C#
asf20
526
namespace Compiler.Helpers { internal enum ArgType { [StringContent("-file")] File, [StringContent("-logs")] LogSource } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/ArgType.cs
C#
asf20
178
using System; namespace Compiler.Helpers { [AttributeUsage(AttributeTargets.Field)] internal class StringContentAttribute : Attribute { public StringContentAttribute(string content) { Content = content; } public string Content { get; private set; } } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/StringContentAttribute.cs
C#
asf20
372
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Compiler.Helpers { internal class LogStringWriterDecorator : System.IO.StringWriter { protected readonly Common.Logging.ILog Logger; public LogStringWriterDecorator(Common.Logging.ILog logger) { Logger = logger; EnableLogSource = false; } public bool EnableLogSource { get; set; } public System.IO.TextReader SourceCode { get; set; } public void TraceLog() { if (EnableLogSource) { Logger.Info(Environment.NewLine + SourceCode.ReadToEnd()); } if (ToString() != string.Empty) { Logger.Error(ToString()); } else { Logger.Info("Build Success."); } } } }
zzxcompiler
trunk/Compiler/Compiler/Helpers/LogStringWriterDecorator.cs
C#
asf20
980
using System; using System.IO; using System.Linq; using System.Threading; using Antlr.Runtime; using Compiler.Helpers; using Compiler.Helpers.ANTLR; namespace Compiler { class Program { static void Main(string[] args) { if (args.Length > 0) { var filePath = string.Empty; if (args.Length >= 2) { if (args.ElementAt(0) == ArgType.File.GetParamString()) { filePath = args.ElementAt(1); } } var lexer = new ZZXLexer(new ANTLRFileStream(filePath)); var commonTokenStream = new CommonTokenStream(lexer); var parser = new ZZXParser(commonTokenStream); var log = new LogStringWriterDecorator(Common.Logging.LogManager.GetCurrentClassLogger()); if (args.Length == 3) { if (args.ElementAt(2) == ArgType.LogSource.GetParamString()) { var reader = File.OpenText(filePath); log.SourceCode = reader; log.EnableLogSource = true; } } parser.TraceDestination = log; parser.program(); Console.WriteLine("Compilation finshed. Number of syntax errors: " + parser.NumberOfSyntaxErrors + "."); log.TraceLog(); } else { Console.WriteLine("Please, run this tool from the command line with the syntax showed below."); Console.WriteLine("Compiler.exe -file [filePath]"); Console.WriteLine("You can also specify '-logs' parameter at the of passed args for the source logging."); Console.WriteLine(); Console.WriteLine("---------------------------------------------------"); Console.WriteLine("Author: Dima Martovoi"); Console.WriteLine("email: dimamartovoi@hotmail.com"); Console.WriteLine("---------------------------------------------------"); Thread.Sleep(4000); } } } }
zzxcompiler
trunk/Compiler/Compiler/Program.cs
C#
asf20
2,328
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Compiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Compiler")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("08948a80-aa70-4955-b5dc-53e09d00fc4a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zzxcompiler
trunk/Compiler/Compiler/Properties/AssemblyInfo.cs
C#
asf20
1,428
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef EVENTSTATUSWIDGET_H #define EVENTSTATUSWIDGET_H #include <QWidget> namespace Ui { class EventStatusWidget; } class EventStatusWidget : public QWidget { Q_OBJECT public: explicit EventStatusWidget(QWidget *parent = 0); ~EventStatusWidget(); void updateEventStatus(); void setFont(const QFont &); private: Ui::EventStatusWidget *ui; QPixmap icons[8]; }; #endif // EVENTSTATUSWIDGET_H
zywhlc-f1lt
src/main_gui/eventstatuswidget.h
C++
gpl3
1,977
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LOGINDIALOG_H #define LOGINDIALOG_H #include <QDialog> #include <QNetworkProxy> namespace Ui { class LoginDialog; } class LoginDialog : public QDialog { Q_OBJECT public: explicit LoginDialog(QWidget *parent = 0); ~LoginDialog(); QString getEmail(); QString getPasswd(); QNetworkProxy getProxy(); bool proxyEnabled(); int exec(QString email="", QString passwd="", QNetworkProxy proxy = QNetworkProxy(), bool proxyEnabled = false); private slots: void on_proxyCheckBox_toggled(bool checked); private: Ui::LoginDialog *ui; }; #endif // LOGINDIALOG_H
zywhlc-f1lt
src/main_gui/logindialog.h
C++
gpl3
2,155
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "delaywidget.h" #include "ui_delaywidget.h" #include <QDebug> DelayWidget::DelayWidget(QWidget *parent) : QWidget(parent), ui(new Ui::DelayWidget), delay(0) { ui->setupUi(this); ui->syncLabel->setVisible(false); // connect(ui->spinBox, SIGNAL(valueChanged(int)), this, SIGNAL(delayChanged(int))); } DelayWidget::~DelayWidget() { delete ui; } void DelayWidget::on_spinBox_valueChanged(int arg1) { int prevDelay = delay; delay = arg1; emit delayChanged(prevDelay, delay); } void DelayWidget::synchronizingTimer(bool sync) { ui->syncLabel->setVisible(sync); }
zywhlc-f1lt
src/main_gui/delaywidget.cpp
C++
gpl3
2,154
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "commentarywidget.h" #include "ui_commentarywidget.h" #include <QScrollBar> #include "../core/eventdata.h" CommentaryWidget::CommentaryWidget(QWidget *parent) : QWidget(parent), ui(new Ui::CommentaryWidget) { ui->setupUi(this); } CommentaryWidget::~CommentaryWidget() { delete ui; } void CommentaryWidget::saveSettings(QSettings &settings) { settings.setValue("ui/commentary_autoscroll", ui->autoScrollBox->isChecked()); } void CommentaryWidget::loadSettings(QSettings &settings) { ui->autoScrollBox->setChecked(settings.value("ui/commentary_autoscroll", true).toBool()); } void CommentaryWidget::setFont(const QFont &font) { ui->commentaryEdit->setFont(font); } QString CommentaryWidget::getCommentary() { return ui->commentaryEdit->toPlainText(); } void CommentaryWidget::clear() { ui->commentaryEdit->clear(); } void CommentaryWidget::update() { int position = ui->commentaryEdit->verticalScrollBar()->sliderPosition(); ui->commentaryEdit->setText(EventData::getInstance().getCommentary()); if (ui->autoScrollBox->isChecked()) { QTextCursor c = ui->commentaryEdit->textCursor(); c.movePosition(QTextCursor::End); ui->commentaryEdit->setTextCursor(c); } else { ui->commentaryEdit->verticalScrollBar()->setSliderPosition(position); } }
zywhlc-f1lt
src/main_gui/commentarywidget.cpp
C++
gpl3
2,899
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "logindialog.h" #include "ui_logindialog.h" LoginDialog::LoginDialog(QWidget *parent) : QDialog(parent), ui(new Ui::LoginDialog) { ui->setupUi(this); } LoginDialog::~LoginDialog() { delete ui; } int LoginDialog::exec(QString email, QString passwd, QNetworkProxy proxy, bool proxyEnabled) { ui->emailEdit->setText(email); ui->passwordEdit->setText(passwd); ui->proxyHostEdit->setText(proxy.hostName()); ui->proxyPortEdit->setValue(proxy.port()); ui->proxyUserEdit->setText(proxy.user()); ui->proxyPasswordEdit->setText(proxy.password()); switch (proxy.type()) { case QNetworkProxy::HttpCachingProxy: ui->proxyTypeBox->setCurrentIndex(0); break; case QNetworkProxy::Socks5Proxy: ui->proxyTypeBox->setCurrentIndex(1); break; default: break; } ui->proxyCheckBox->setChecked(proxyEnabled); return QDialog::exec(); } QString LoginDialog::getEmail() { return ui->emailEdit->text(); } QString LoginDialog::getPasswd() { return ui->passwordEdit->text(); } QNetworkProxy LoginDialog::getProxy() { QNetworkProxy proxy; // if (ui->proxyCheckBox->isChecked()) { proxy.setHostName(ui->proxyHostEdit->text()); proxy.setUser(ui->proxyUserEdit->text()); proxy.setPassword(ui->proxyPasswordEdit->text()); proxy.setPort(ui->proxyPortEdit->value()); switch (ui->proxyTypeBox->currentIndex()) { case 0: proxy.setType(QNetworkProxy::HttpCachingProxy); break; case 1: proxy.setType(QNetworkProxy::Socks5Proxy); break; } } return proxy; } bool LoginDialog::proxyEnabled() { return ui->proxyCheckBox->isChecked(); } void LoginDialog::on_proxyCheckBox_toggled(bool checked) { ui->proxyBox->setEnabled(checked); // if (checked) // setGeometry(x(), y(), width(), 290); // else // setGeometry(x(), y(), width(), 135); }
zywhlc-f1lt
src/main_gui/logindialog.cpp
C++
gpl3
3,477
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "driverinfolabel.h" #include <QPainter> #include <QDebug> #include "../core/colorsmanager.h" DriverInfoLabel::DriverInfoLabel(QWidget *parent) : QWidget(parent), driverData(0) { backgroundPixmap = QPixmap(":/ui_icons/label-small.png"); } QSize DriverInfoLabel::sizeHint() { return backgroundPixmap.size(); } QSize DriverInfoLabel::minimumSize() { return backgroundPixmap.size(); } void DriverInfoLabel::update() { if (height() < sizeHint().height()) { QSize size = backgroundPixmap.size(); size.setHeight(size.height() + 10); setMinimumSize(size); updateGeometry(); } repaint(); } void DriverInfoLabel::paintEvent(QPaintEvent *) { if (driverData == 0) return; QPainter p; p.begin(this); int x = (width() - backgroundPixmap.width())/2; QColor color = /*QColor(170, 170, 170);*/ColorsManager::getInstance().getCarColor(driverData->getNumber()); int numX = x + 105; int numY = 1; p.setBrush(color); p.drawRect(numX, numY, 30, 20); numX = x + 20; numY = 30; p.drawPixmap(x, 0, backgroundPixmap); QString txt = QString::number(driverData->getPosition()); if (driverData->getPosition() < 10) txt = " " + txt; p.setFont(QFont("Arial", 20, 100)); p.setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::BACKGROUND))); if (driverData->isInPits()) p.setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::PIT))); p.drawText(numX, numY, txt); txt = driverData->getDriverName(); p.setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE))); p.setFont(QFont("Arial", 10, 100)); numX = x + 140; numY = 15; p.drawText(numX, numY, txt); numX = x + 120; numY = 35; txt = SeasonData::getInstance().getTeamName(driverData->getNumber()); p.drawText(numX, numY, txt); p.setPen(QColor(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND))); txt = QString::number(driverData->getNumber()); if (driverData->getNumber() < 10) txt = " " + txt; numX = x + 115; numY = 15; p.drawText(numX, numY, txt); numX = x + 63; numY = 4; p.drawPixmap(numX, numY, ImagesFactory::getInstance().getHelmetsFactory().getHelmet(driverData->getNumber(), 30)); }
zywhlc-f1lt
src/main_gui/driverinfolabel.cpp
C++
gpl3
3,893
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "ltitemdelegate.h" #include <QDebug> #include <QPainter> #include "models/ltmodel.h" void LTItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItem viewOption(option); QColor color = index.data(Qt::ForegroundRole).value<QColor>(); if (color.isValid()) { if (color != option.palette.color(QPalette::WindowText)) viewOption.palette.setColor(QPalette::HighlightedText, color); } QItemDelegate::paint(painter, viewOption, index); } //========================================= void LTMainItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { LTItemDelegate::paint(painter, option, index); if (index.column() == 2 && drawCars) { const DriverData *dd = static_cast<const LTModel*>(index.model())->getDriverData(index); if (dd == 0 || dd->getCarID() <= 0) return; QPixmap &pix = ImagesFactory::getInstance().getCarThumbnailsFactory().getCarThumbnail(dd->getNumber(), thumbnailsSize);//getCarImage(dd); if (!pix.isNull()) { int x = option.rect.x() + (option.rect.width() - pix.rect().width())/2; int y = option.rect.y() + (option.rect.height() - pix.rect().height())/2; painter->drawPixmap(x, y, pix.width(), pix.height(), pix); } } }
zywhlc-f1lt
src/main_gui/ltitemdelegate.cpp
C++
gpl3
2,972
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "preferencesdialog.h" #include "ui_preferencesdialog.h" #include <iostream> #include <QColorDialog> #include <QFontDialog> #include "../core/colorsmanager.h" #include "../net/networksettings.h" PreferencesDialog::PreferencesDialog(QWidget *parent) : QDialog(parent), ui(new Ui::PreferencesDialog) { ui->setupUi(this); // settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "pieczar", "F1LT", this); settings = new QSettings("f1lt.ini", QSettings::IniFormat, this); dcDialog = new DriverColorsDialog(this); } PreferencesDialog::~PreferencesDialog() { // std::cout<<settings->fileName().toStdString()<<std::endl; delete ui; } int PreferencesDialog::exec(QSettings *set) { colors = ColorsManager::getInstance().getColors(); setButtonColor(ui->colorGreenButton, colors[LTPackets::GREEN]); setButtonColor(ui->colorWhiteButton, colors[LTPackets::WHITE]); setButtonColor(ui->colorVioletButton, colors[LTPackets::VIOLET]); setButtonColor(ui->colorRedButton, colors[LTPackets::RED]); setButtonColor(ui->colorYellowButton, colors[LTPackets::YELLOW]); setButtonColor(ui->colorCyanButton, colors[LTPackets::CYAN]); settings = set; QString sbuf = settings->value("fonts/main_family").toString(); mainFont.setFamily(sbuf); int ibuf = settings->value("fonts/main_size").toInt(); mainFont.setPointSize(ibuf); ibuf = settings->value("fonts/main_weight").toInt(); mainFont.setWeight(ibuf); bool bbuf = settings->value("fonts/main_italic").toBool(); mainFont.setItalic(bbuf); sbuf = settings->value("fonts/commentary_family").toString(); commentaryFont.setFamily(sbuf); ibuf = settings->value("fonts/commentary_size").toInt(); commentaryFont.setPointSize(ibuf); ibuf = settings->value("fonts/commentary_weight").toInt(); commentaryFont.setWeight(ibuf); bbuf = settings->value("fonts/commentary_italic").toBool(); commentaryFont.setItalic(bbuf); setSplitterOpaqueResize(settings->value("ui/ltresize").toBool()); setAutoRecord(settings->value("ui/auto_record").toBool()); setDrawCarThumbnails(settings->value("ui/car_thumbnails").toBool()); setDrawTrackerClassification(settings->value("ui/draw_tracker_classification").toBool()); setAutoStopRecord(settings->value("ui/auto_stop_record", -1).toInt()); setAutoSaveRecord(settings->value("ui/auto_save_record", -1).toInt()); setCheckForUpdatesEnabled(settings->value("ui/check_for_updates", true).toBool()); QNetworkProxy proxy = NetworkSettings::getInstance().getProxy(); ui->proxyHostEdit->setText(proxy.hostName()); ui->proxyPortEdit->setValue(proxy.port()); ui->proxyUserEdit->setText(proxy.user()); ui->proxyPasswordEdit->setText(proxy.password()); switch (proxy.type()) { case QNetworkProxy::HttpCachingProxy: ui->proxyTypeBox->setCurrentIndex(0); break; case QNetworkProxy::Socks5Proxy: ui->proxyTypeBox->setCurrentIndex(1); break; default: break; } ui->proxyCheckBox->setChecked(NetworkSettings::getInstance().usingProxy()); return QDialog::exec(); } void PreferencesDialog::on_buttonBox_accepted() { settings->setValue("fonts/main_family", mainFont.family()); settings->setValue("fonts/main_size", QString::number(mainFont.pointSize())); settings->setValue("fonts/main_weight", QString::number(mainFont.weight())); settings->setValue("fonts/main_italic", QString::number(mainFont.italic())); settings->setValue("fonts/commentary_family", commentaryFont.family()); settings->setValue("fonts/commentary_size", QString::number(commentaryFont.pointSize())); settings->setValue("fonts/commentary_weight", QString::number(commentaryFont.weight())); settings->setValue("fonts/commentary_italic", QString::number(commentaryFont.italic())); settings->setValue("ui/ltresize", isSplitterOpaqueResize()); settings->setValue("ui/car_thumbnails", drawCarThumbnails()); settings->setValue("ui/auto_record", isAutoRecord()); settings->setValue("ui/auto_stop_record", getAutoStopRecord()); settings->setValue("ui/auto_save_record", getAutoSaveRecord()); settings->setValue("ui/auto_connect", isAutoConnect()); settings->setValue("ui/draw_tracker_classification", drawTrackerClassification()); settings->setValue("ui/check_for_updates", isCheckForUpdatesEnabled()); ColorsManager::getInstance().setColors(colors); } QNetworkProxy PreferencesDialog::getProxy() { QNetworkProxy proxy; // if (ui->proxyCheckBox->isChecked()) { proxy.setHostName(ui->proxyHostEdit->text()); proxy.setUser(ui->proxyUserEdit->text()); proxy.setPassword(ui->proxyPasswordEdit->text()); proxy.setPort(ui->proxyPortEdit->value()); switch (ui->proxyTypeBox->currentIndex()) { case 0: proxy.setType(QNetworkProxy::HttpCachingProxy); break; case 1: proxy.setType(QNetworkProxy::Socks5Proxy); break; } } return proxy; } bool PreferencesDialog::proxyEnabled() { return ui->proxyCheckBox->isChecked(); } void PreferencesDialog::setFonts(const QFont &f1, const QFont &f2) { mainFont = f1; ui->mainFontButton->setText(QString("%1, %2").arg(mainFont.family()).arg(mainFont.pointSize())); ui->mainFontButton->setFont(mainFont); commentaryFont = f2; ui->commentaryFontButton->setText(QString("%1, %2").arg(commentaryFont.family()).arg(commentaryFont.pointSize())); ui->commentaryFontButton->setFont(commentaryFont); } void PreferencesDialog::on_mainFontButton_clicked() { bool ok = false; mainFont = QFontDialog::getFont(&ok, mainFont, this); ui->mainFontButton->setText(QString("%1, %2").arg(mainFont.family()).arg(mainFont.pointSize())); } void PreferencesDialog::on_commentaryFontButton_clicked() { bool ok = false; commentaryFont = QFontDialog::getFont(&ok, commentaryFont, this); ui->commentaryFontButton->setText(QString("%1, %2").arg(commentaryFont.family()).arg(commentaryFont.pointSize())); } void PreferencesDialog::setMainFont(const QFont &f) { ui->mainFontButton->setFont(f); mainFont = f; } void PreferencesDialog::setCommentaryFont(const QFont &f) { ui->commentaryFontButton->setFont(f); commentaryFont = f; } bool PreferencesDialog::isSplitterOpaqueResize() { return ui->ltCheckBox->isChecked(); } void PreferencesDialog::setSplitterOpaqueResize(bool val) { ui->ltCheckBox->setChecked(val); } bool PreferencesDialog::drawCarThumbnails() { return ui->thumbnailsCheckBox->isChecked(); } void PreferencesDialog::setDrawCarThumbnails(bool val) { ui->thumbnailsCheckBox->setChecked(val); } void PreferencesDialog::setAutoRecord(bool val) { ui->autoRecordBox->setChecked(val); } bool PreferencesDialog::isAutoRecord() { return ui->autoRecordBox->isChecked(); } void PreferencesDialog::setAutoStopRecord(int val) { if (val >= 0) { ui->autoStopRecordSpinBox->setEnabled(true); ui->autoStopRecordBox->setChecked(true); ui->autoStopRecordSpinBox->setValue(val); } else { ui->autoStopRecordSpinBox->setEnabled(false); ui->autoStopRecordBox->setChecked(false); } } int PreferencesDialog::getAutoStopRecord() { if (!ui->autoStopRecordBox->isChecked()) return -1; else return ui->autoStopRecordSpinBox->value(); } void PreferencesDialog::setAutoSaveRecord(int val) { if (val >= 0) { ui->autoSaveRecordSpinBox->setEnabled(true); ui->autoSaveRecordBox->setChecked(true); ui->autoSaveRecordSpinBox->setValue(val); } else { ui->autoSaveRecordSpinBox->setEnabled(false); ui->autoSaveRecordBox->setChecked(false); } } int PreferencesDialog::getAutoSaveRecord() { if (!ui->autoSaveRecordBox->isChecked()) return -1; else return ui->autoSaveRecordSpinBox->value(); } void PreferencesDialog::on_autoStopRecordBox_toggled(bool checked) { ui->autoStopRecordSpinBox->setEnabled(checked); } void PreferencesDialog::setAutoConnect(bool val) { ui->autoConnectBox->setChecked(val); } bool PreferencesDialog::isAutoConnect() { return ui->autoConnectBox->isChecked(); } bool PreferencesDialog::drawTrackerClassification() { return ui->trackerBox->isChecked(); } void PreferencesDialog::setDrawTrackerClassification(bool val) { ui->trackerBox->setChecked(val); } void PreferencesDialog::setCheckForUpdatesEnabled(bool val) { ui->updateCheckBox->setChecked(val); } bool PreferencesDialog::isCheckForUpdatesEnabled() { return ui->updateCheckBox->isChecked(); } void PreferencesDialog::on_proxyCheckBox_toggled(bool checked) { ui->proxyBox->setEnabled(checked); } void PreferencesDialog::on_pushButton_clicked() { colors[LTPackets::WHITE] = ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE); setButtonColor(ui->colorWhiteButton, colors[LTPackets::WHITE]); } void PreferencesDialog::on_pushButton_2_clicked() { colors[LTPackets::CYAN] = ColorsManager::getInstance().getDefaultColor(LTPackets::CYAN); setButtonColor(ui->colorCyanButton, colors[LTPackets::CYAN]); } void PreferencesDialog::on_pushButton_3_clicked() { colors[LTPackets::YELLOW] = ColorsManager::getInstance().getDefaultColor(LTPackets::YELLOW); setButtonColor(ui->colorYellowButton, colors[LTPackets::YELLOW]); } void PreferencesDialog::on_pushButton_4_clicked() { colors[LTPackets::PIT] = ColorsManager::getInstance().getDefaultColor(LTPackets::PIT); colors[LTPackets::RED] = ColorsManager::getInstance().getDefaultColor(LTPackets::RED); setButtonColor(ui->colorRedButton, colors[LTPackets::PIT]); } void PreferencesDialog::on_pushButton_5_clicked() { colors[LTPackets::GREEN] = ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN); setButtonColor(ui->colorGreenButton, colors[LTPackets::GREEN]); } void PreferencesDialog::on_pushButton_6_clicked() { colors[LTPackets::VIOLET] = ColorsManager::getInstance().getDefaultColor(LTPackets::VIOLET); setButtonColor(ui->colorVioletButton, colors[LTPackets::VIOLET]); } void PreferencesDialog::on_colorWhiteButton_clicked() { QColor color = QColorDialog::getColor(colors[LTPackets::WHITE], this); if (color.isValid()) { colors[LTPackets::WHITE] = color; setButtonColor(ui->colorWhiteButton, color); } } void PreferencesDialog::on_colorCyanButton_clicked() { QColor color = QColorDialog::getColor(colors[LTPackets::CYAN], this); if (color.isValid()) { colors[LTPackets::CYAN] = color; setButtonColor(ui->colorCyanButton, color); } } void PreferencesDialog::on_colorYellowButton_clicked() { QColor color = QColorDialog::getColor(colors[LTPackets::YELLOW], this); if (color.isValid()) { colors[LTPackets::YELLOW] = color; setButtonColor(ui->colorYellowButton, color); } } void PreferencesDialog::on_colorRedButton_clicked() { QColor color = QColorDialog::getColor(colors[LTPackets::PIT], this); if (color.isValid()) { colors[LTPackets::PIT] = color; colors[LTPackets::RED] = color; setButtonColor(ui->colorRedButton, color); } } void PreferencesDialog::on_colorGreenButton_clicked() { QColor color = QColorDialog::getColor(colors[LTPackets::GREEN], this); if (color.isValid()) { colors[LTPackets::GREEN] = color; setButtonColor(ui->colorGreenButton, color); } } void PreferencesDialog::on_colorVioletButton_clicked() { QColor color = QColorDialog::getColor(colors[LTPackets::VIOLET], this); if (color.isValid()) { colors[LTPackets::VIOLET] = color; setButtonColor(ui->colorVioletButton, color); } } void PreferencesDialog::setButtonColor(QToolButton *button, QColor color) { QString styleSheet = "background-color: rgb(" + QString("%1, %2, %3").arg(color.red()).arg(color.green()).arg(color.blue()) + ");\n "\ "border-style: solid;\n "\ "border-width: 1px;\n "\ "border-radius: 3px;\n "\ "border-color: rgb(153, 153, 153);\n "\ "padding: 3px;\n"; button->setStyleSheet(styleSheet); } void PreferencesDialog::on_pushButton_7_clicked() { colors = ColorsManager::getInstance().getDefaultColors(); setButtonColor(ui->colorWhiteButton, colors[LTPackets::WHITE]); setButtonColor(ui->colorCyanButton, colors[LTPackets::CYAN]); setButtonColor(ui->colorYellowButton, colors[LTPackets::YELLOW]); setButtonColor(ui->colorRedButton, colors[LTPackets::RED]); setButtonColor(ui->colorGreenButton, colors[LTPackets::GREEN]); setButtonColor(ui->colorVioletButton, colors[LTPackets::VIOLET]); } void PreferencesDialog::on_pushButton_8_clicked() { if (dcDialog->exec()) emit driversColorsChanged(); } void PreferencesDialog::on_autoSaveRecordBox_toggled(bool checked) { ui->autoSaveRecordSpinBox->setEnabled(checked); }
zywhlc-f1lt
src/main_gui/preferencesdialog.cpp
C++
gpl3
14,616
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LTTABLEVIEW_H #define LTTABLEVIEW_H #include <QTableView> class LTTableView : public QTableView { Q_OBJECT public: explicit LTTableView(QWidget *parent = 0); signals: void headerClicked(int column); public slots: void updateColumn(QModelIndex index); protected: void keyPressEvent(QKeyEvent *event); void resizeEvent(QResizeEvent *event); void wheelEvent(QWheelEvent *event); void mousePressEvent(QMouseEvent *event); }; #endif // LTTABLEVIEW_H
zywhlc-f1lt
src/main_gui/lttableview.h
C++
gpl3
2,047
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "aboutdialog.h" #include "ui_aboutdialog.h" #include "../core/f1ltcore.h" #include "../core/f1ltcore.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); ui->versionLabel->setText("F1LT " + F1LTCore::programVersion()); loadChangelog(); loadLicense(); } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::loadChangelog() { QFile file(":/files/CHANGELOG"); if (file.open(QIODevice::ReadOnly)) { ui->textEdit->setText(file.readAll()); } } void AboutDialog::loadLicense() { QFile licenseFile(":/files/LICENSE"); if (licenseFile.open(QIODevice::ReadOnly)) { ui->licenseEdit->setText(licenseFile.readAll()); } }
zywhlc-f1lt
src/main_gui/aboutdialog.cpp
C++
gpl3
2,306
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef RACEMODEL_H #define RACEMODEL_H #include <QIcon> #include "ltmodel.h" #include "../../core/eventdata.h" class RaceModel : public LTModel { public: RaceModel(QObject *parent = 0); virtual int rowCount(const QModelIndex & parent = QModelIndex()) const; virtual int columnCount(const QModelIndex & parent = QModelIndex()) const; virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; virtual QVariant driverRowData(const DriverData &dd, const QModelIndex &index, int role) const; virtual QVariant headerRowData(const QModelIndex &index, int role) const; virtual QVariant extraRowData(const QModelIndex &index, int role) const; QVariant gapToSelected(const DriverData &dd, int column) const; virtual void getDiffColumns(int &low, int &high) { low = 5; high = 9; } virtual bool selectDriver(int id, int column) { LTModel::selectDriver(id, column); if (column == 0 || (column >= 5 && column < 10)) { updateLT(); return true; } return false; } QVariant getIcon(const DriverData &) const; private: EventData &eventData; QIcon arrowIcons[2]; }; #endif // RACEMODEL_H
zywhlc-f1lt
src/main_gui/models/racemodel.h
C++
gpl3
2,800
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "speedrecordsmodel.h" #include "../../core/colorsmanager.h" #include "../../core/eventdata.h" #include <QModelIndex> SpeedRecordsModel::SpeedRecordsModel(QObject *parent) : QAbstractTableModel(parent) { } int SpeedRecordsModel::rowCount(const QModelIndex &) const { return 15; } int SpeedRecordsModel::columnCount(const QModelIndex &) const { return 5; } void SpeedRecordsModel::update() { QModelIndex topLeft = QAbstractTableModel::index(0, 0); QModelIndex bottomRight = QAbstractTableModel::index(rowCount()-1, columnCount()-1); emit dataChanged(topLeft, bottomRight); } QVariant SpeedRecordsModel::data(const QModelIndex & index, int role) const { if (index.row() == 0 || index.row() == 8) return headerData(index, role); if (index.row() == 7) return QVariant(); int row = index.row() - 1; int sector = index.column() < 2 ? 1 : 2; if (index.row() > 8) { row = index.row() - 9; sector = index.column() < 2 ? 3 : 4; } switch (index.column()) { case 0: if (role == Qt::DisplayRole) return EventData::getInstance().getSessionRecords().getSectorSpeed(sector, row).getDriverName(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::WHITE); return QVariant(); case 1: if (role == Qt::DisplayRole) return EventData::getInstance().getSessionRecords().getSectorSpeed(sector, row).getSpeed(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); return QVariant(); case 3: if (role == Qt::DisplayRole) { if (sector == 2) return EventData::getInstance().getSessionRecords().getSectorSpeed(sector, row).getDriverName(); return EventData::getInstance().getSessionRecords().getSpeedTrap(row).getDriverName(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::WHITE); return QVariant(); case 4: if (role == Qt::DisplayRole) { if (sector == 2) return EventData::getInstance().getSessionRecords().getSectorSpeed(sector, row).getSpeed(); return EventData::getInstance().getSessionRecords().getSpeedTrap(row).getSpeed(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); } return QVariant(); } QVariant SpeedRecordsModel::headerData(const QModelIndex & index, int role) const { QString s1 = "Sector 1"; QString s2 = "Sector 2"; if (index.row() == 8) { s1 = "Sector 3"; s2 = "Speed trap"; } if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return s1; case 1: return "KPH"; case 3: return s2; case 4: return "KPH"; } } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::DEFAULT); if (role == Qt::TextAlignmentRole) { if (index.column() == 1 || index.column() == 4) return (int)(Qt::AlignVCenter | Qt::AlignRight); } return QVariant(); }
zywhlc-f1lt
src/main_gui/models/speedrecordsmodel.cpp
C++
gpl3
5,221
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef QUALIMODEL_H #define QUALIMODEL_H #include "ltmodel.h" #include "../../core/eventdata.h" #include <QDebug> class QualiLessThan { public: QualiLessThan(int period, const LapTime &time107) : qPeriod(period), time107p(time107) { } bool operator()(DriverData *d1, DriverData *d2) { if (qPeriod > 0) { if (d1->getQualiTime(qPeriod).isValid() && d2->getQualiTime(qPeriod).isValid()) { if (d1->getQualiTime(qPeriod) == d2->getQualiTime(qPeriod)) return (d1->getPosition() < d2->getPosition()); return (d1->getQualiTime(qPeriod) < d2->getQualiTime(qPeriod)); } } // else { //this is only because LT server likes to mess things up when drivers are out of 107% //during Q1 and doesn't sort them properly if (((!d1->getQualiTime(1).isValid() || d1->getQualiTime(1) > time107p) || (!d2->getQualiTime(1).isValid() || d2->getQualiTime(1) > time107p)) && (d1->getQualiTime(1).isValid() != d2->getQualiTime(1).isValid())) { return d1->getQualiTime(1) < d2->getQualiTime(1); } } if (d1->getColorData().driverColor() == LTPackets::PIT || d1->getColorData().driverColor() == LTPackets::RED || d2->getColorData().driverColor() == LTPackets::PIT || d2->getColorData().driverColor() == LTPackets::RED) { int q = EventData::getInstance().getQualiPeriod(); while (q > 0) { if (d1->getQualiTime(q).isValid() && d2->getQualiTime(q).isValid()) { if (d1->getQualiTime(q) == d2->getQualiTime(q)) return (d1->getPosition() < d2->getPosition()); return (d1->getQualiTime(q) < d2->getQualiTime(q)); } --q; } } // if (qPeriod == 0 && EventData::getInstance().isSessionStarted() && d1->getLastLap().getTime().isValid() && d2->getLastLap().getTime().isValid()) // return d1->getLastLap().getTime() < d2->getLastLap().getTime(); return (d1->getPosition() < d2->getPosition()); } private: int qPeriod; LapTime time107p; }; class QualiModel : public LTModel { public: QualiModel(QObject *parent = 0); virtual void updateLT(); virtual int rowCount(const QModelIndex & parent = QModelIndex()) const; virtual int columnCount(const QModelIndex & parent = QModelIndex()) const; virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; virtual QVariant driverRowData(const DriverData &dd, const QModelIndex &index, int role) const; virtual QVariant headerRowData(const QModelIndex &index, int role) const; virtual QVariant extraRowData(const QModelIndex &index, int role) const; QVariant gapToSelected(const DriverData &dd, int column) const; virtual void getDiffColumns(int &low, int &high) { low = 4; high = 9; } virtual bool selectDriver(int id, int column) { LTModel::selectDriver(id, column); if (column == 0 || (column >= 4 && column < 10)) { updateLT(); return true; } return false; } LapTime findBestQ1Time() const; virtual void headerClicked(int column); private: EventData &eventData; int qualiPeriodSelected; }; #endif // QUALIMODEL_H
zywhlc-f1lt
src/main_gui/models/qualimodel.h
C++
gpl3
5,077
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "racemodel.h" #include "../../core/colorsmanager.h" #include <QPixmap> RaceModel::RaceModel(QObject *parent) : LTModel(parent), eventData(EventData::getInstance()) { arrowIcons[0] = QIcon(QPixmap(":/track/up-arrow.png").scaledToHeight(10, Qt::SmoothTransformation)); arrowIcons[1] = QIcon(QPixmap(":/track/down-arrow.png").scaledToHeight(10, Qt::SmoothTransformation)); } int RaceModel::rowCount(const QModelIndex &) const { return eventData.getDriversData().size() + 3; } int RaceModel::columnCount(const QModelIndex &) const { return 11; } QVariant RaceModel::data(const QModelIndex &index, int role) const { int row = index.row()-1; if (row >= 0 && row < driversData.size() && driversData[row] != 0) { DriverData &dd = *driversData[row];//eventData.getDriverDataByPos(row); return driverRowData(dd, index, role); } else if (index.row() == 0) return headerRowData(index, role); else return extraRowData(index, role); } QVariant RaceModel::driverRowData(const DriverData &dd, const QModelIndex &index, int role) const { switch (index.column()) { case 0: if (role == Qt::DisplayRole && dd.getPosition() > 0 && !dd.isRetired()) { return QString("%1.").arg(dd.getPosition()); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().positionColor()); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); break; case 1: if (role == Qt::DisplayRole && dd.getPosition() > 0) return dd.getNumber(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().numberColor()); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); if (role == Qt::DecorationRole) return getIcon(dd); break; case 2: // if (role == Qt::DecorationRole) // return getCarImage(dd); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 3: if (role == Qt::DisplayRole) return dd.getDriverName(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().driverColor()); break; case 4: if (role == Qt::DisplayRole) return dd.getLastLap().getGap(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().gapColor()); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 5: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 5) return gapToSelected(dd, 5); return dd.getLastLap().getInterval(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().intervalColor()); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 6: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 5 && dd.getLastLap().getTime().isValid()) return gapToSelected(dd, 6); return dd.getLastLap().getTime().toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().lapTimeColor()); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; if (role == Qt::ToolTipRole) return "Best lap: " + dd.getSessionRecords().getBestLap().getTime().toString() + QString(" (L%1)").arg(dd.getSessionRecords().getBestLap().getLapNumber()); break; break; case 7: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 5 && dd.getLastLap().getSectorTime(1).isValid()) return gapToSelected(dd, 7); return dd.getLastLap().getSectorTime(1).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(1)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 8: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 5 && dd.getLastLap().getSectorTime(2).isValid()) return gapToSelected(dd, 8); return dd.getLastLap().getSectorTime(2).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(2)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 9: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 5 && dd.getLastLap().getSectorTime(3).isValid()) return gapToSelected(dd, 9); return dd.getLastLap().getSectorTime(3).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(3)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 10: if (role == Qt::DisplayRole && dd.getNumPits() > 0) return dd.getNumPits(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().numLapsColor()); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; } return QVariant(); } QVariant RaceModel::headerRowData(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return "P"; case 1: return ""; case 2: return ""; case 3: return "Name"; case 4: return "Gap"; case 5: return "Interval"; case 6: return "Time"; case 7: return "S1"; case 8: return "S2"; case 9: return "S3"; case 10: return "Pit"; default: break; } } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::DEFAULT); if (role == Qt::TextAlignmentRole) { if (index.column() >= 0 && index.column() <= 1) return (int)(Qt::AlignVCenter | Qt::AlignRight); if (index.column() >= 4) return Qt::AlignCenter; } return QVariant(); } QVariant RaceModel::extraRowData(const QModelIndex &index, int role) const { if (index.row() == rowCount()-2) return QVariant(); if (role == Qt::DisplayRole && eventData.getSessionRecords().getFastestLap().getDriverName() != "") { switch (index.column()) { case 1: return "FL:"; case 3: return eventData.getSessionRecords().getFastestLap().getDriverName(); case 4: return "lap"; case 5: return eventData.getSessionRecords().getFastestLap().getLapNumber(); case 6: return eventData.getSessionRecords().getFastestLap().getTime().toString(); } } else if (role == Qt::ForegroundRole && (index.column() == 3 || index.column() == 5 || index.column() == 6)) return ColorsManager::getInstance().getColor(LTPackets::VIOLET); else if (role == Qt::ForegroundRole && (index.column() == 1 || index.column() == 4)) return ColorsManager::getInstance().getColor(LTPackets::DEFAULT); if (role == Qt::TextAlignmentRole && index.column() == 1) return (int)(Qt::AlignVCenter | Qt::AlignRight); if (role == Qt::TextAlignmentRole && (index.column() >= 4 && index.column() <= 6)) return Qt::AlignCenter; return QVariant(); } QVariant RaceModel::gapToSelected(const DriverData &dd, int column) const { DriverData currD = eventData.getDriverDataById(selectedDriver.first); if (column == 6 && (selectedDriver.first == dd.getCarID() || !currD.getLastLap().getTime().isValid() || !dd.getLastLap().getTime().isValid())) { return dd.getLastLap().getTime().toString(); } if (column == 5) { if (selectedDriver.first == dd.getCarID()) return ""; return eventData.calculateInterval(dd, currD, -1);//EventData.getInstance().lapsCompleted);//.driversData.get(currentCar-1).lastLap.numLap); } if (column == 6) { QString gap = DriverData::calculateGap(dd.getLastLap().getTime(), currD.getLastLap().getTime()); if (gap.size() > 0 && gap[0] != '-') gap = "+" + gap; return gap; } if (column > 6) { int sector = column - 6; if ((selectedDriver.first == dd.getCarID()) || !currD.getLastLap().getSectorTime(sector).isValid()) return dd.getLastLap().getSectorTime(sector).toString(); else { QString gap = DriverData::calculateGap(dd.getLastLap().getSectorTime(sector), currD.getLastLap().getSectorTime(sector)); if ((gap.size() > 0) && (gap[0] != '-') && (gap != "0.000")) gap = "+" + gap; return gap.left(gap.size()-2); } } return ""; } QVariant RaceModel::getIcon(const DriverData &dd) const { if (!dd.isRetired() && dd.getNumber() > 0) { int lastPos = 0, prevPos = 0; if (dd.getLapData().size() > 1) { lastPos = dd.getLastLap().getPosition(); prevPos = dd.getLapData()[dd.getLapData().size()-2].getPosition(); } else if (!dd.getPositionHistory().isEmpty()) { lastPos = dd.getLastLap().getPosition(); prevPos = dd.getPositionHistory()[dd.getLastLap().getLapNumber() == 1 ? 0 : dd.getPositionHistory().size()-1]; } if (lastPos != prevPos) return (lastPos < prevPos ? arrowIcons[0] : arrowIcons[1]); } return QVariant(); }
zywhlc-f1lt
src/main_gui/models/racemodel.cpp
C++
gpl3
12,300
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "qualimodel.h" #include "../../core/colorsmanager.h" #include <QDebug> QualiModel::QualiModel(QObject *parent) : LTModel(parent), eventData(EventData::getInstance()), qualiPeriodSelected(0) { } int QualiModel::rowCount(const QModelIndex &) const { return eventData.getDriversData().size() + 3; } int QualiModel::columnCount(const QModelIndex &) const { return 11; } void QualiModel::headerClicked(int column) { int col = column - 3; if (col == eventData.getQualiPeriod() || col == 3)//col >= 1 && col <= 2) { if (qualiPeriodSelected == 0) qualiPeriodSelected = col * 10; else qualiPeriodSelected = 0; updateLT(); } else if (col == 1 || col == 2) { if (qualiPeriodSelected == col) qualiPeriodSelected = col * 10; else if (qualiPeriodSelected == col * 10) qualiPeriodSelected = 0; else qualiPeriodSelected = col; updateLT(); } } void QualiModel::updateLT() { //driversData = QList<DriverData>(EventData::getInstance().getDriversData()); gatherDriversData(); int qPeriod = qualiPeriodSelected >= 10 ? qualiPeriodSelected / 10 : qualiPeriodSelected; qSort(driversData.begin(), driversData.end(), QualiLessThan(qPeriod, EventData::getInstance().getSessionRecords().getQualiBestTime(1).calc107p())); QModelIndex topLeft = QAbstractTableModel::index(firstRow(), 0); QModelIndex bottomRight = QAbstractTableModel::index(rowCount()-1, columnCount()-1); emit dataChanged(topLeft, bottomRight); } QVariant QualiModel::data(const QModelIndex &index, int role) const { int row = index.row()-1; if (row >= 0 && row < driversData.size()) { DriverData &dd = *driversData[row];//eventData.getDriverDataByPos(row); return driverRowData(dd, index, role); } else if (index.row() == 0) return headerRowData(index, role); else return extraRowData(index, role); } QVariant QualiModel::driverRowData(const DriverData &dd, const QModelIndex &index, int role) const { switch (index.column()) { case 0: if (role == Qt::DisplayRole) return QString("%1.").arg(index.row());//dd.getPosition()); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().positionColor()); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); break; case 1: if (role == Qt::DisplayRole) return dd.getNumber(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().numberColor()); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); break; case 2: // if (role == Qt::DecorationRole) // return getCarImage(dd); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 3: if (role == Qt::DisplayRole) return dd.getDriverName(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().driverColor()); break; case 4: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4) return gapToSelected(dd, 4); if (qualiPeriodSelected == 10 && &dd != driversData.first()) return DriverData::calculateGap(dd.getQualiTime(1), driversData.first()->getQualiTime(1)); return dd.getQualiTime(1).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().qualiTimeColor(1)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 5: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4) return gapToSelected(dd, 5); if (qualiPeriodSelected == 20 && &dd != driversData.first()) return DriverData::calculateGap(dd.getQualiTime(2), driversData.first()->getQualiTime(2)); return dd.getQualiTime(2).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().qualiTimeColor(2)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 6: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4) return gapToSelected(dd, 6); if (qualiPeriodSelected == 30 && &dd != driversData.first()) return DriverData::calculateGap(dd.getQualiTime(3), driversData.first()->getQualiTime(3)); return dd.getQualiTime(3).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().qualiTimeColor(3)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; break; case 7: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4 && dd.getLastLap().getSectorTime(1).isValid()) return gapToSelected(dd, 7); return dd.getLastLap().getSectorTime(1).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(1)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 8: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4 && dd.getLastLap().getSectorTime(2).isValid()) return gapToSelected(dd, 8); return dd.getLastLap().getSectorTime(2).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(2)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 9: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4 && dd.getLastLap().getSectorTime(3).isValid()) return gapToSelected(dd, 9); return dd.getLastLap().getSectorTime(3).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(3)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 10: if (role == Qt::DisplayRole && dd.getLastLap().getLapNumber() > 0) return dd.getLastLap().getLapNumber(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().numLapsColor()); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; } return QVariant(); } QVariant QualiModel::headerRowData(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return "P"; case 1: return ""; case 2: return ""; case 3: return "Name"; case 4: return "Q1"; case 5: return "Q2"; case 6: return "Q3"; case 7: return "S1"; case 8: return "S2"; case 9: return "S3"; case 10: return "Laps"; default: break; } } if (role == Qt::ForegroundRole) { if (index.column() >= 4 && index.column() <= 6) { int col = index.column() - 3; if (col == qualiPeriodSelected) return ColorsManager::getInstance().getColor(LTPackets::WHITE); if (col * 10 == qualiPeriodSelected) return ColorsManager::getInstance().getColor(LTPackets::YELLOW); } return ColorsManager::getInstance().getColor(LTPackets::DEFAULT); } if (role == Qt::TextAlignmentRole) { if (index.column() >= 0 && index.column() <= 1) return (int)(Qt::AlignVCenter | Qt::AlignRight); if (index.column() >= 4) return Qt::AlignCenter; } return QVariant(); } QVariant QualiModel::extraRowData(const QModelIndex &index, int role) const { if (index.row() == rowCount()-2) return QVariant(); if (role == Qt::DisplayRole && !driversData.isEmpty() && driversData.first()->getQualiTime(1).isValid()) { switch (index.column()) { case 3: return "Q1 107% time"; case 4: LapTime q1Best = EventData::getInstance().getSessionRecords().getQualiBestTime(1);//findBestQ1Time(); if (qualiPeriodSelected == 10) return DriverData::calculateGap(q1Best.calc107p(), q1Best); return q1Best.calc107p().toString(); } } else if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::RED); if (role == Qt::TextAlignmentRole && index.column() == 4) return Qt::AlignCenter; return QVariant(); } QVariant QualiModel::gapToSelected(const DriverData &dd, int column) const { int qPeriod = column-3; DriverData currD = eventData.getDriverDataById(selectedDriver.first); if (qPeriod > 0 && qPeriod < 4) { if ((selectedDriver.first == dd.getCarID()) || !currD.getQualiTime(qPeriod).isValid()) return dd.getQualiTime(qPeriod).toString(); QString gap = DriverData::calculateGap(dd.getQualiTime(qPeriod), currD.getQualiTime(qPeriod)); if (gap.size() > 0 && gap[0] != '-') gap = "+" + gap; return gap; } if (column > 6) { int sector = column - 6; if ((selectedDriver.first == dd.getCarID()) || !currD.getLastLap().getSectorTime(sector).isValid()) return dd.getLastLap().getSectorTime(sector).toString(); else { QString gap = DriverData::calculateGap(dd.getLastLap().getSectorTime(sector), currD.getLastLap().getSectorTime(sector)); if ((gap.size() > 0) && (gap[0] != '-') && (gap != "0.000")) gap = "+" + gap; return gap.left(gap.size()-2); } } return ""; } LapTime QualiModel::findBestQ1Time() const { LapTime bestTime = driversData.first()->getQualiTime(1); for (int i = 1; i < driversData.size(); ++i) { if (driversData[i]->getQualiTime(1) < bestTime) bestTime = driversData[i]->getQualiTime(1); } return bestTime; }
zywhlc-f1lt
src/main_gui/models/qualimodel.cpp
C++
gpl3
12,981
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef SPEEDRECORDSMODEL_H #define SPEEDRECORDSMODEL_H #include <QAbstractTableModel> class SpeedRecordsModel : public QAbstractTableModel { public: SpeedRecordsModel(QObject *parent = 0); virtual int rowCount(const QModelIndex & parent = QModelIndex()) const; virtual int columnCount(const QModelIndex & parent = QModelIndex()) const; virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; QVariant headerData(const QModelIndex & index, int role = Qt::DisplayRole) const; void update(); }; #endif // SPEEDRECORDSMODEL_H
zywhlc-f1lt
src/main_gui/models/speedrecordsmodel.h
C++
gpl3
2,124
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef PITSTOPSMODEL_H #define PITSTOPSMODEL_H #include <QAbstractTableModel> #include "../../core/eventdata.h" class PitStopsModel : public QAbstractTableModel { Q_OBJECT public: explicit PitStopsModel(QObject *parent = 0); virtual int rowCount(const QModelIndex & parent = QModelIndex()) const; virtual int columnCount(const QModelIndex & parent = QModelIndex()) const; virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) { beginInsertRows(parent, row, row + count); endInsertRows(); return true; } virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) { beginRemoveRows(parent, row, row + count - 1); endRemoveRows(); return true; } QVariant headerData(const QModelIndex & index, int role = Qt::DisplayRole) const; void update(); signals: public slots: private: int rows; struct PitStopAtom { double time; int lap; QString driver; int pos; bool operator <(const PitStopAtom &psa) const { return time < psa.time; } }; void getPitstops(const QVector<DriverData> &driversData); QList< PitStopAtom > pitStops; }; #endif // PITSTOPSMODEL_H
zywhlc-f1lt
src/main_gui/models/pitstopsmodel.h
C++
gpl3
2,950
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef FASTESTLAPSMODEL_H #define FASTESTLAPSMODEL_H #include <QAbstractTableModel> #include "../../core/eventdata.h" class FastestLapsModel : public QAbstractTableModel { Q_OBJECT public: explicit FastestLapsModel(QObject *parent = 0); virtual int rowCount(const QModelIndex & parent = QModelIndex()) const; virtual int columnCount(const QModelIndex & parent = QModelIndex()) const; virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; QVariant headerData(const QModelIndex & index, int role = Qt::DisplayRole) const; void update(); QList<LapData> &getFastestLaps() { return fastestLaps; } signals: public slots: private: QList<LapData> fastestLaps; }; #endif // FASTESTLAPSMODEL_H
zywhlc-f1lt
src/main_gui/models/fastestlapsmodel.h
C++
gpl3
2,318
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "driverlaphistorymodel.h" #include "../../core/colorsmanager.h" #include <QDebug> DriverLapHistoryModel::DriverLapHistoryModel(QObject *parent) : QAbstractTableModel(parent), rows(1) { } int DriverLapHistoryModel::rowCount(const QModelIndex &) const { // int rows = driverData->getLapData().size() + 1; return rows; //EventData::getInstance().getDriversData().size()+1; } int DriverLapHistoryModel::columnCount(const QModelIndex &) const { return 8; } void DriverLapHistoryModel::update(DriverData *dd) { driverData = dd; int laps = dd->getLapData().size(); // if ((laps+1) > rows) // { // insertRows(rows, laps + 1 - rows); // rows = laps + 1; // } // else if ((laps+1) < rows) // { // removeRows(laps + 1, rows - laps - 1); // rows = laps + 1; // } if (laps >= rows) { insertRows(rows, laps - rows); rows = laps + 1; } else if (laps < rows) { removeRows(laps + 1, rows - laps - 1); rows = laps + 1; } QModelIndex topLeft = QAbstractTableModel::index(0, 0); QModelIndex bottomRight = QAbstractTableModel::index(rowCount()-1, columnCount()-1); emit dataChanged(topLeft, bottomRight); } QVariant DriverLapHistoryModel::data(const QModelIndex & index, int role) const { if (driverData == 0) return QVariant(); if (index.row() == 0) return headerData(index, role); if (index.row() > driverData->getLapData().size()) return QVariant(); const LapData &ld = driverData->getLapData()[driverData->getLapData().size() - index.row()]; switch (index.column()) { case 0: if (role == Qt::DisplayRole) return ld.getLapNumber(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::WHITE); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter + Qt::AlignRight); case 1: if (role == Qt::DisplayRole) return ld.getPosition(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::CYAN); case 2: if (role == Qt::DisplayRole) { if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT) { if (ld.getPosition() != 1) return ld.getGap(); return ""; } else if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) return QString("%1 (Q%2)").arg(SeasonData::getInstance().getSessionDefaults().correctQualiTime(ld.getQualiLapExtraData().getSessionTime(), ld.getQualiLapExtraData().getQualiPeriod()).toString("mm:ss")). arg(ld.getQualiLapExtraData().getQualiPeriod()); else if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT) return SeasonData::getInstance().getSessionDefaults().correctFPTime(ld.getPracticeLapExtraData().getSessionTime()).toString("h:mm:ss"); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter + Qt::AlignRight); case 3: return getLapTime(ld, role); case 4: if (role == Qt::DisplayRole) { if (ld.getTime() != driverData->getSessionRecords().getBestLap().getTime() && ld.getTime().isValid()) return DriverData::calculateGap(ld.getTime(), driverData->getSessionRecords().getBestLap().getTime()); return ""; } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter + Qt::AlignRight); case 5: return getSectorTime(ld, role, 1); case 6: return getSectorTime(ld, role, 2); case 7: return getSectorTime(ld, role, 3); } return QVariant(); } QVariant DriverLapHistoryModel::getLapTime(const LapData &ld, int role) const { QColor color = ColorsManager::getInstance().getColor(LTPackets::WHITE); QString s = ld.getTime().toString(); if (ld.getLapNumber() == driverData->getSessionRecords().getBestLap().getLapNumber()) color = ColorsManager::getInstance().getColor(LTPackets::GREEN); if (ld.getLapNumber() == EventData::getInstance().getSessionRecords().getFastestLap().getLapNumber() && driverData->getDriverName() == EventData::getInstance().getSessionRecords().getFastestLap().getDriverName()) color = ColorsManager::getInstance().getColor(LTPackets::VIOLET); if (ld.getTime().toString() == "IN PIT") { color = ColorsManager::getInstance().getColor(LTPackets::PIT); s = QString("IN PIT (%1)").arg(driverData->getPitTime(ld.getLapNumber())); } else if (ld.getTime().toString() == "RETIRED" || ld.getTime().toString().contains("LAP")) color = ColorsManager::getInstance().getColor(LTPackets::PIT); else if (ld.getRaceLapExtraData().isSCLap()) color = ColorsManager::getInstance().getColor(LTPackets::YELLOW); if ((EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT && ld.getPracticeLapExtraData().isApproxLap()) || (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT && ld.getQualiLapExtraData().isApproxLap())) color = ColorsManager::getInstance().getColor(LTPackets::CYAN); if (role == Qt::DisplayRole) return s; if (role == Qt::ForegroundRole) return color; if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); return QVariant(); } QVariant DriverLapHistoryModel::getSectorTime(const LapData &ld, int role, int sector) const { QColor color = ColorsManager::getInstance().getColor(LTPackets::WHITE); QString s = ld.getSectorTime(sector).toString(); if (ld.getLapNumber() == driverData->getSessionRecords().getBestSectorLapNumber(sector)) { color = ColorsManager::getInstance().getColor(LTPackets::GREEN); } if (ld.getLapNumber() == EventData::getInstance().getSessionRecords().getSectorRecord(sector).getLapNumber() && driverData->getDriverName() == EventData::getInstance().getSessionRecords().getSectorRecord(sector).getDriverName()) color = ColorsManager::getInstance().getColor(LTPackets::VIOLET); if (role == Qt::DisplayRole) return s; if (role == Qt::ForegroundRole) return color; if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); return QVariant(); } QVariant DriverLapHistoryModel::headerData(const QModelIndex & index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return "Lap"; case 1: return "P"; case 2: if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT) return "Gap"; return "S. time"; case 3: return "Time"; case 4: return "Diff."; case 5: return "S1"; case 6: return "S2"; case 7: return "S3"; } } if (role == Qt::TextAlignmentRole) { switch (index.column()) { case 0: return (int)(Qt::AlignVCenter + Qt::AlignRight); case 1: return (int)(Qt::AlignVCenter + Qt::AlignRight); case 2: return (int)(Qt::AlignVCenter + Qt::AlignRight); case 3: return (int)(Qt::AlignCenter); case 4: return (int)(Qt::AlignVCenter + Qt::AlignRight); case 5: return (int)(Qt::AlignCenter); case 6: return (int)(Qt::AlignCenter); case 7: return (int)(Qt::AlignCenter); } } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::DEFAULT); return QVariant(); }
zywhlc-f1lt
src/main_gui/models/driverlaphistorymodel.cpp
C++
gpl3
9,813
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef PRACTICEMODEL_H #define PRACTICEMODEL_H #include "ltmodel.h" #include "../../core/eventdata.h" class PracticeModel : public LTModel { public: PracticeModel(QObject *parent = 0); virtual int rowCount(const QModelIndex & parent = QModelIndex()) const; virtual int columnCount(const QModelIndex & parent = QModelIndex()) const; virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; virtual QVariant driverRowData(const DriverData &dd, const QModelIndex &index, int role) const; virtual QVariant headerRowData(const QModelIndex &index, int role) const; virtual QVariant extraRowData(const QModelIndex &index, int role) const; QVariant gapToSelected(const DriverData &dd, int column) const; virtual void getDiffColumns(int &low, int &high) { low = 4; high = 8; } virtual bool selectDriver(int id, int column) { LTModel::selectDriver(id, column); if (column == 0 || (column >= 4 && column < 9)) { updateLT(); return true; } return false; } private: EventData &eventData; }; #endif // PRACTICEMODEL_H
zywhlc-f1lt
src/main_gui/models/practicemodel.h
C++
gpl3
2,725
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "fastestlapsmodel.h" #include "../../core/colorsmanager.h" FastestLapsModel::FastestLapsModel(QObject *parent) : QAbstractTableModel(parent) { } int FastestLapsModel::rowCount(const QModelIndex &) const { return EventData::getInstance().getDriversData().size() + 1; } int FastestLapsModel::columnCount(const QModelIndex &) const { return 8; } void FastestLapsModel::update() { EventData &ed = EventData::getInstance(); for (int i = 0; i < ed.getDriversData().size(); ++i) { DriverData &dd = ed.getDriversData()[i]; if (fastestLaps.size() <= i) fastestLaps.append(dd.getSessionRecords().getBestLap()); else fastestLaps[i] = dd.getSessionRecords().getBestLap(); } qSort(fastestLaps); QModelIndex topLeft = QAbstractTableModel::index(0, 0); QModelIndex bottomRight = QAbstractTableModel::index(rowCount()-1, columnCount()-1); emit dataChanged(topLeft, bottomRight); } QVariant FastestLapsModel::data(const QModelIndex & index, int role) const { if (index.row() == 0) return headerData(index, role); LapData ld = fastestLaps[index.row() - 1]; DriverData *dd = EventData::getInstance().getDriverDataByIdPtr(ld.getCarID()); if (dd == 0) return QVariant(); switch (index.column()) { case 0: if (role == Qt::DisplayRole) { if (ld.getTime().isValid()) return QString("%1.").arg(index.row()); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::CYAN); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); return QVariant(); case 1: if (role == Qt::DisplayRole) return dd->getDriverName(); if (role == Qt::ForegroundRole) { if (index.row() == 1) return ColorsManager::getInstance().getColor(LTPackets::VIOLET); return ColorsManager::getInstance().getColor(LTPackets::WHITE); } return QVariant(); case 2: if (role == Qt::DisplayRole) return ld.getTime().toString(); if (role == Qt::ForegroundRole) { if (index.row() == 1) return ColorsManager::getInstance().getColor(LTPackets::VIOLET); return ColorsManager::getInstance().getColor(LTPackets::GREEN); } if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); return QVariant(); case 3: if (role == Qt::DisplayRole && index.row() != 1) return DriverData::calculateGap(ld.getTime(), fastestLaps.first().getTime()); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); return QVariant(); case 4: if (role == Qt::DisplayRole) return ld.getSectorTime(1).toString(); if (role == Qt::ForegroundRole) { if (ld.getLapNumber() == EventData::getInstance().getSessionRecords().getSectorRecord(1).getLapNumber() && dd->getDriverName() == EventData::getInstance().getSessionRecords().getSectorRecord(1).getDriverName()) return ColorsManager::getInstance().getColor(LTPackets::VIOLET); if (ld.getLapNumber() == dd->getSessionRecords().getBestSectorLapNumber(1)) return ColorsManager::getInstance().getColor(LTPackets::GREEN); return ColorsManager::getInstance().getColor(LTPackets::WHITE); } if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); case 5: if (role == Qt::DisplayRole) return ld.getSectorTime(2).toString(); if (role == Qt::ForegroundRole) { if (ld.getLapNumber() == EventData::getInstance().getSessionRecords().getSectorRecord(2).getLapNumber() && dd->getDriverName() == EventData::getInstance().getSessionRecords().getSectorRecord(2).getDriverName()) return ColorsManager::getInstance().getColor(LTPackets::VIOLET); if (ld.getLapNumber() == dd->getSessionRecords().getBestSectorLapNumber(2)) return ColorsManager::getInstance().getColor(LTPackets::GREEN); return ColorsManager::getInstance().getColor(LTPackets::WHITE); } if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); case 6: if (role == Qt::DisplayRole) return ld.getSectorTime(3).toString(); if (role == Qt::ForegroundRole) { if (ld.getLapNumber() == EventData::getInstance().getSessionRecords().getSectorRecord(3).getLapNumber() && dd->getDriverName() == EventData::getInstance().getSessionRecords().getSectorRecord(3).getDriverName()) return ColorsManager::getInstance().getColor(LTPackets::VIOLET); if (ld.getLapNumber() == dd->getSessionRecords().getBestSectorLapNumber(3)) return ColorsManager::getInstance().getColor(LTPackets::GREEN); return ColorsManager::getInstance().getColor(LTPackets::WHITE); } if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); case 7: if (role == Qt::DisplayRole) { if (ld.getTime().isValid()) { if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) return QString("%1 (Q%2)").arg(ld.getLapNumber()).arg(ld.getQualiLapExtraData().getQualiPeriod()); return ld.getLapNumber(); } } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::WHITE); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); } return QVariant(); } QVariant FastestLapsModel::headerData(const QModelIndex & index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return "P"; case 1: return "Name"; case 2: return "Time"; case 3: return "Gap"; case 4: return "S1"; case 5: return "S2"; case 6: return "S3"; case 7: return "Lap"; } } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::DEFAULT); if (role == Qt::TextAlignmentRole) { if (index.column() >= 2 && index.column() <= 6) return (int)(Qt::AlignCenter); if (index.column() == 0 || index.column() == 7) return (int)(Qt::AlignVCenter | Qt::AlignRight); } return QVariant(); }
zywhlc-f1lt
src/main_gui/models/fastestlapsmodel.cpp
C++
gpl3
8,837
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "ltmodel.h" #include <QDebug> #include "../../core/eventdata.h" LTModel::LTModel(QObject *parent) : QAbstractTableModel(parent) { selectedDriver = QPair<int, int>(0, 0); } void LTModel::updateLT() { //driversData = QList<DriverData>(EventData::getInstance().getDriversData()); gatherDriversData(); qSort(driversData.begin(), driversData.end(), LessThan()); QModelIndex topLeft = QAbstractTableModel::index(firstRow(), 0); QModelIndex bottomRight = QAbstractTableModel::index(rowCount()-1, columnCount()-1); emit dataChanged(topLeft, bottomRight); } const DriverData *LTModel::getDriverData(const QModelIndex &index) const { int row = index.row(); if (row >= 1 && row <= EventData::getInstance().getDriversData().size() && (row - 1) < driversData.size()) { return driversData[row-1]; } return 0; } bool LTModel::indexInDriverRowsData(const QModelIndex &index) const { int row = index.row(); if (row >= 1 && row <= EventData::getInstance().getDriversData().size()) return true; return false; } QModelIndex LTModel::indexOf(int driverId) { for (int i = 0; i < driversData.size(); ++i) { if (driversData[i]->getCarID() == driverId) { QModelIndex idx = index(i+1, 0); return idx; } } // DriverData dd = EventData::getInstance().getDriverDataById(driverId); // if (dd.getCarID() > 0) // { // } return QModelIndex(); } void LTModel::gatherDriversData() { driversData.clear(); for (int i = 0; i < EventData::getInstance().getDriversData().size(); ++i) { DriverData *dd = &EventData::getInstance().getDriversData()[i]; driversData.append(dd); } }
zywhlc-f1lt
src/main_gui/models/ltmodel.cpp
C++
gpl3
3,288
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "practicemodel.h" #include "../../core/colorsmanager.h" PracticeModel::PracticeModel(QObject *parent) : LTModel(parent), eventData(EventData::getInstance()) { } int PracticeModel::rowCount(const QModelIndex &) const { return eventData.getDriversData().size() + 3; } int PracticeModel::columnCount(const QModelIndex &) const { return 10; } QVariant PracticeModel::data(const QModelIndex &index, int role) const { int row = index.row()-1; if (row >= 0 && row < driversData.size()) { DriverData &dd = *driversData[row];//eventData.getDriverDataByPos(row); return driverRowData(dd, index, role); } else if (index.row() == 0) return headerRowData(index, role); else return extraRowData(index, role); } QVariant PracticeModel::driverRowData(const DriverData &dd, const QModelIndex &index, int role) const { switch (index.column()) { case 0: if (role == Qt::DisplayRole) return QString("%1.").arg(dd.getPosition()); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().positionColor()); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); break; case 1: if (role == Qt::DisplayRole) return dd.getNumber(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().numberColor()); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter | Qt::AlignRight); break; case 2: // if (role == Qt::DecorationRole) // return getCarImage(dd); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 3: if (role == Qt::DisplayRole) return dd.getDriverName(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().driverColor()); break; case 4: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4) return gapToSelected(dd, 4); return dd.getLastLap().getTime().toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().lapTimeColor()); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 5: if (role == Qt::DisplayRole) { if (dd.getPosition() == 1) return ""; return dd.getLastLap().getGap(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().gapColor()); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 6: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4 && dd.getLastLap().getSectorTime(1).isValid()) return gapToSelected(dd, 6); return dd.getLastLap().getSectorTime(1).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(1)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 7: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4 && dd.getLastLap().getSectorTime(2).isValid()) return gapToSelected(dd, 7); return dd.getLastLap().getSectorTime(2).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(2)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 8: if (role == Qt::DisplayRole) { if (selectedDriver.first != 0 && selectedDriver.second >= 4 && dd.getLastLap().getSectorTime(3).isValid()) return gapToSelected(dd, 8); return dd.getLastLap().getSectorTime(3).toString(); } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().sectorColor(3)); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; case 9: if (role == Qt::DisplayRole && dd.getLastLap().getLapNumber() > 0) return dd.getLastLap().getLapNumber(); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(dd.getColorData().numLapsColor()); if (role == Qt::TextAlignmentRole) return Qt::AlignCenter; break; } return QVariant(); } QVariant PracticeModel::headerRowData(const QModelIndex &index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { case 0: return "P"; case 1: return ""; case 2: return ""; case 3: return "Name"; case 4: return "Best"; case 5: return "Gap"; case 6: return "S1"; case 7: return "S2"; case 8: return "S3"; case 9: return "Laps"; default: break; } } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::DEFAULT); if (role == Qt::TextAlignmentRole) { if (index.column() >= 0 && index.column() <= 1) return (int)(Qt::AlignVCenter | Qt::AlignRight); if (index.column() >= 4) return Qt::AlignCenter; } return QVariant(); } QVariant PracticeModel::extraRowData(const QModelIndex &index, int role) const { if (index.row() == rowCount()-2) return QVariant(); if (role == Qt::DisplayRole && !eventData.getDriverDataByPos(1).getLapData().isEmpty() && !driversData.isEmpty()) { switch (index.column()) { case 3: return "107% time"; case 4: return driversData.first()->getSessionRecords().getBestLap().getTime().calc107p().toString();//eventData.getDriverDataByPos(1).getSessionRecords().getBestLap().getTime().calc107p().toString(); case 5: return DriverData::calculateGap(driversData.first()->getSessionRecords().getBestLap().getTime().calc107p(), driversData.first()->getSessionRecords().getBestLap().getTime()); } } else if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::RED); if (role == Qt::TextAlignmentRole && ((index.column() == 4) || (index.column() == 5))) return Qt::AlignCenter; return QVariant(); } QVariant PracticeModel::gapToSelected(const DriverData &dd, int column) const { DriverData currD = eventData.getDriverDataById(selectedDriver.first); if (column == 4) { if ((selectedDriver.first == dd.getCarID()) || !currD.getLastLap().getTime().isValid()) return dd.getLastLap().getTime().toString(); QString gap = DriverData::calculateGap(dd.getLastLap().getTime(), currD.getLastLap().getTime()); if (gap.size() > 0 && gap[0] != '-') gap = "+" + gap; return gap; } if (column > 5) { int sector = column - 5; if ((selectedDriver.first == dd.getCarID()) || !currD.getLastLap().getSectorTime(sector).isValid()) return dd.getLastLap().getSectorTime(sector).toString(); else { QString gap = DriverData::calculateGap(dd.getLastLap().getSectorTime(sector), currD.getLastLap().getSectorTime(sector)); if ((gap.size() > 0) && (gap[0] != '-') && (gap != "0.000")) gap = "+" + gap; return gap.left(gap.size()-2); } } return ""; }
zywhlc-f1lt
src/main_gui/models/practicemodel.cpp
C++
gpl3
9,934
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef DRIVERLAPHISTORYMODEL_H #define DRIVERLAPHISTORYMODEL_H #include <QAbstractTableModel> #include <QDebug> #include "../../core/eventdata.h" class DriverLapHistoryModel : public QAbstractTableModel { Q_OBJECT public: explicit DriverLapHistoryModel(QObject *parent = 0); virtual int rowCount(const QModelIndex & parent = QModelIndex()) const; virtual int columnCount(const QModelIndex & parent = QModelIndex()) const; virtual QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; virtual bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()) { beginInsertRows(parent, row, row + count); endInsertRows(); return true; } virtual bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()) { beginRemoveRows(parent, row, row + count - 1); endRemoveRows(); return true; } QVariant getLapTime(const LapData &, int role) const; QVariant getSectorTime(const LapData &, int role, int sector) const; QVariant headerData(const QModelIndex & index, int role = Qt::DisplayRole) const; void update(DriverData *dd); void clear() { driverData = 0; rows = 0; reset(); } signals: public slots: private: DriverData *driverData; int rows; }; #endif // DRIVERLAPHISTORYMODEL_H
zywhlc-f1lt
src/main_gui/models/driverlaphistorymodel.h
C++
gpl3
2,956
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LTMODEL_H #define LTMODEL_H #include <QAbstractTableModel> #include <QDebug> #include <QList> #include <QPixmap> #include "../../core/eventdata.h" class LessThan { public: bool operator()(DriverData *d1, DriverData *d2) { if (d1->getPosition() <= 0) return false; if (d2->getPosition() <= 0) return true; return (d1->getPosition() < d2->getPosition()); } }; class LTModel : public QAbstractTableModel { Q_OBJECT public: explicit LTModel(QObject *parent = 0); virtual void updateLT(); virtual const DriverData *getDriverData(const QModelIndex &index) const; virtual bool indexInDriverRowsData(const QModelIndex &index) const; virtual int firstRow() const { return 1; } virtual int lastRow() const { return EventData::getInstance().getDriversData().size(); } virtual int driverRows() const { return EventData::getInstance().getDriversData().size(); } virtual QVariant driverRowData(const DriverData &, const QModelIndex &index, int role) const = 0; virtual QVariant headerRowData(const QModelIndex &index, int role) const = 0; virtual QVariant extraRowData(const QModelIndex &index, int role) const = 0; virtual QModelIndex indexOf(int driverId); virtual void getDiffColumns(int &low, int &high) { low = 0; high = 0; } virtual bool selectDriver(int id, int column) { int low, high; getDiffColumns(low, high); if (selectedDriver.first == id) { if (column >= low && column <= high) { if (selectedDriver.second >= low && selectedDriver.second <= high) { selectedDriver.second = 0; } else selectedDriver.second = column; } } else { selectedDriver.first = id; if (column >= low && column <= high) selectedDriver.second = column; } return true; } virtual void headerClicked(int) { } void clearData() { driversData.clear(); } signals: public slots: protected: virtual void gatherDriversData(); QList<DriverData *> driversData; QPair<int, int> selectedDriver; //first - driver id, second - column }; #endif // LTMODEL_H
zywhlc-f1lt
src/main_gui/models/ltmodel.h
C++
gpl3
3,992
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "pitstopsmodel.h" #include "../../core/colorsmanager.h" PitStopsModel::PitStopsModel(QObject *parent) : QAbstractTableModel(parent), rows(1) { } int PitStopsModel::rowCount(const QModelIndex &) const { return rows; } int PitStopsModel::columnCount(const QModelIndex &) const { return 6; } void PitStopsModel::update() { getPitstops(EventData::getInstance().getDriversData()); int ps = pitStops.size(); if (ps >= rows) { insertRows(rows, ps - rows); rows = ps + 1; } else if (ps < rows) { removeRows(ps + 1, rows - ps - 1); rows = ps + 1; } QModelIndex topLeft = QAbstractTableModel::index(0, 0); QModelIndex bottomRight = QAbstractTableModel::index(rowCount()-1, columnCount()-1); emit dataChanged(topLeft, bottomRight); } QVariant PitStopsModel::data(const QModelIndex & index, int role) const { if (index.row() == 0) return headerData(index, role); if (index.row() > pitStops.size()) return QVariant(); PitStopAtom ps = pitStops[index.row() - 1]; switch (index.column()) { case 0: if (role == Qt::DisplayRole) return QString("%1.").arg(index.row()); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::CYAN); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter + Qt::AlignRight); case 1: if (role == Qt::DisplayRole) return ps.lap; if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter + Qt::AlignRight); case 2: if (role == Qt::DisplayRole) return SeasonData::getInstance().getDriverNo(ps.driver); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::WHITE); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignVCenter + Qt::AlignRight); case 3: if (role == Qt::DisplayRole) return ps.driver; if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::WHITE); return QVariant(); case 4: if (role == Qt::DisplayRole) return QString::number(ps.time, 'f', 1); if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); case 5: if (role == Qt::DisplayRole) { QString str = QString("%1").arg(ps.pos); if (ps.pos > 0) str = "+" + str; return str; } if (role == Qt::ForegroundRole) { if (ps.pos > 0) return ColorsManager::getInstance().getColor(LTPackets::GREEN); if (ps.pos < 0) return ColorsManager::getInstance().getColor(LTPackets::RED); return ColorsManager::getInstance().getColor(LTPackets::WHITE); } if (role == Qt::TextAlignmentRole) return (int)(Qt::AlignCenter); } return QVariant(); } QVariant PitStopsModel::headerData(const QModelIndex & index, int role) const { if (role == Qt::DisplayRole) { switch (index.column()) { case 1: return "Lap"; case 3: return "Name"; case 4: return "Time"; case 5: return "+/- P"; } } if (role == Qt::TextAlignmentRole) { switch (index.column()) { case 1: return (int)(Qt::AlignVCenter + Qt::AlignRight); case 2: return (int)(Qt::AlignVCenter + Qt::AlignRight); case 4: return (int)(Qt::AlignCenter); case 5: return (int)(Qt::AlignCenter); } } if (role == Qt::ForegroundRole) return ColorsManager::getInstance().getColor(LTPackets::DEFAULT); return QVariant(); } void PitStopsModel::getPitstops(const QVector<DriverData> &driversData) { pitStops.clear(); for (int i = 0; i < driversData.size(); ++i) { for (int j = 0; j < driversData[i].getPitStops().size(); ++j) { PitStopAtom pitAtom; pitAtom.driver = driversData[i].getDriverName(); pitAtom.lap = driversData[i].getPitStops()[j].getPitLap(); pitAtom.time = driversData[i].getPitStops()[j].getPitTime().toDouble(); LapData ld1 = driversData[i].getLapData(driversData[i].getPitStops()[j].getPitLap()); LapData ld2 = driversData[i].getLapData(driversData[i].getPitStops()[j].getPitLap()+1); pitAtom.pos = 0; if (ld1.getCarID() != -1 && ld2.getCarID() != -1) pitAtom.pos = ld1.getPosition() - ld2.getPosition(); // QPair< QPair<double, int>, QString > pitAtom(QPair<double, int>(driversData[i].pitData[j].pitTime.toDouble(), driversData[i].pitData[j].pitLap), driversData[i].driver); pitStops.append(pitAtom); } } qSort(pitStops); }
zywhlc-f1lt
src/main_gui/models/pitstopsmodel.cpp
C++
gpl3
6,946
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "driverdatawidget.h" #include "ui_driverdatawidget.h" #include <QClipboard> #include <QResizeEvent> #include <QScrollBar> #include <QSplitter> #include "ltitemdelegate.h" #include "../core/colorsmanager.h" #include "../core/trackrecords.h" DriverDataWidget::DriverDataWidget(QWidget *parent) : QWidget(parent), ui(new Ui::DriverDataWidget), currentDriver(0), eventData(EventData::getInstance()) { ui->setupUi(this); posChart = new DriverDataChart(1, 24, ColorsManager::getInstance().getColor(LTPackets::CYAN), this); QColor colors[5]; colors[0] = ColorsManager::getInstance().getColor(LTPackets::RED); colors[1] = ColorsManager::getInstance().getColor(LTPackets::WHITE); colors[2] = ColorsManager::getInstance().getColor(LTPackets::GREEN); colors[3] = ColorsManager::getInstance().getColor(LTPackets::VIOLET); colors[4] = ColorsManager::getInstance().getColor(LTPackets::YELLOW); lapTimeChart = new LapTimeChart(colors, this); gapChart = new GapChart(ColorsManager::getInstance().getColor(LTPackets::YELLOW), this); ui->chartsTableWidget->setColumnWidth(0, ui->chartsTableWidget->width()); ui->lapTimeChartTableWidget->setColumnWidth(0, ui->lapTimeChartTableWidget->width()); ui->infoWidget->setVisible(false); driverLapHistoryModel = new DriverLapHistoryModel(this); ui->tableView->setModel(driverLapHistoryModel); ui->tableView->setItemDelegate(new LTItemDelegate(this)); // ui->toolBox->insertItem(0, gapChart, QIcon(), "Position chart"); // ui->stackedWidget->addWidget(gapChart); // QSplitter *splitter = new QSplitter(Qt::Vertical, ui->tab_3); // splitter->addWidget(posChart); // splitter->addWidget(lapTimeChart); // ui->verticalLayout_4->addWidget(splitter); ui->chartsTableWidget->insertRow(0); ui->chartsTableWidget->setRowHeight(0, 20); QTableWidgetItem *item = new QTableWidgetItem("Position chart"); item->setTextAlignment(Qt::AlignCenter); ui->chartsTableWidget->setItem(0, 0, item); ui->chartsTableWidget->insertRow(1); ui->chartsTableWidget->setCellWidget(1, 0, posChart); ui->chartsTableWidget->setRowHeight(1, 200); ui->lapTimeChartTableWidget->insertRow(0); ui->lapTimeChartTableWidget->setRowHeight(0, 20); item = new QTableWidgetItem("Lap time chart"); item->setTextAlignment(Qt::AlignCenter); ui->lapTimeChartTableWidget->setItem(0, 0, item); ui->lapTimeChartTableWidget->insertRow(1); ui->lapTimeChartTableWidget->setCellWidget(1, 0, lapTimeChart); ui->lapTimeChartTableWidget->setRowHeight(1, ui->lapTimeChartTableWidget->height()-20); ui->chartsTableWidget->insertRow(2); ui->chartsTableWidget->setRowHeight(2, 20); item = new QTableWidgetItem("Gap to leader chart"); item->setTextAlignment(Qt::AlignCenter); ui->chartsTableWidget->setItem(2, 0, item); ui->chartsTableWidget->insertRow(3); ui->chartsTableWidget->setCellWidget(3, 0, gapChart); ui->chartsTableWidget->setRowHeight(3, 200); } DriverDataWidget::~DriverDataWidget() { delete driverLapHistoryModel; delete ui; } void DriverDataWidget::updateDriverInfo(const DriverData &driverData) { if (!ui->infoWidget->isVisible()) ui->infoWidget->setVisible(true); QString s; QPalette palette; ui->driverInfoLabel->setDriver(&driverData); ui->driverInfoLabel->update(); ui->carImageLabel->setPixmap(SeasonData::getInstance().getCarImg(driverData.getNumber())); if (eventData.getEventType() == LTPackets::RACE_EVENT) { ui->gridLabel->setText("Grid position:"); if (!driverData.getPositionHistory().isEmpty()) s = QString("%1").arg(driverData.getPositionHistory()[0]); else s = ""; } else { ui->gridLabel->setText("Laps completed:"); int laps = driverData.getLastLap().getLapNumber(); if (laps < 0) laps = 0; s = QString::number(laps); } palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->gridPositionLabel->setText(s); ui->gridPositionLabel->setPalette(palette); s = driverData.getLastLap().getGap(); if (driverData.getPosition() == 1) s = ""; palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->gapLabel->setText(s); ui->gapLabel->setPalette(palette); if (eventData.getEventType() == LTPackets::RACE_EVENT) { LapTime lt = driverData.getLastLap().getTime(); s = lt.toString(); if (lt != driverData.getSessionRecords().getBestLap().getTime() && lt.isValid()) s += " (+" + DriverData::calculateGap(lt, driverData.getSessionRecords().getBestLap().getTime()) + ")"; QPalette palette = ui->lastLapLabel->palette(); if (lt.toString() == "RETIRED" || lt.toString() == "IN PIT" || lt.toString() == "OUT") palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::RED)); else palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->lastLapLabel->setPalette(palette); } else { LapTime lt = driverData.getLastLap().getTime(); if (!driverData.getLapData().isEmpty()) lt = driverData.getLapData().last().getTime(); s = lt.toString(); if (lt.isValid() && lt != driverData.getSessionRecords().getBestLap().getTime()) s += " (+" + DriverData::calculateGap(lt, driverData.getSessionRecords().getBestLap().getTime()) + ")"; if (lt.isValid()) palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); else palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::RED)); ui->lastLapLabel->setPalette(palette); } ui->lastLapLabel->setText(s); ui->bestLapLabel->setText(driverData.getSessionRecords().getBestLap().getTime().toString()); palette = ui->bestLapLabel->palette(); if (driverData.getDriverName() == eventData.getSessionRecords().getFastestLap().getDriverName() && driverData.getSessionRecords().getBestLap().getTime() == eventData.getSessionRecords().getFastestLap().getTime()) palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); else palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); ui->bestLapLabel->setPalette(palette); if (driverData.getSessionRecords().getBestSectorTime(1).isValid() && driverData.getSessionRecords().getBestSectorTime(2).isValid() && driverData.getSessionRecords().getBestSectorTime(3).isValid()) { ui->approxLapLabel->setText(LapData::sumSectors(driverData.getSessionRecords().getBestSectorTime(1), driverData.getSessionRecords().getBestSectorTime(2), driverData.getSessionRecords().getBestSectorTime(3))); } else ui->approxLapLabel->setText(""); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::CYAN)); ui->approxLapLabel->setPalette(palette); if (eventData.getEventType() == LTPackets::RACE_EVENT) { ui->pitStopsLabel->setText("Pit stops:"); palette = ui->pitStopsLabel->palette(); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); ui->pitStopsLabel->setPalette(palette); ui->numPitsLabel->setText(QString::number(driverData.getNumPits())); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::PIT)); ui->numPitsLabel->setPalette(palette); if (!ui->numPitsLabel->isVisible()) ui->numPitsLabel->setVisible(true); } else { palette = ui->pitStopsLabel->palette(); if (driverData.isInPits()) { ui->pitStopsLabel->setText("In pits"); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::PIT)); } else { ui->pitStopsLabel->setText("On track"); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); } ui->pitStopsLabel->setPalette(palette); if (ui->numPitsLabel->isVisible()) ui->numPitsLabel->setVisible(false); } } void DriverDataWidget::printDriverData(int id) { if (id <= 0) return; printDriverChart(id); printDriverRecords(id); printDriverRelatedCommentary(id); currentDriver = id; DriverData *driverData = eventData.getDriverDataByIdPtr(id); if (driverData != 0) { updateDriverInfo(*driverData); driverLapHistoryModel->update(driverData); for (int i = 0; i < driverLapHistoryModel->rowCount(); ++i) ui->tableView->setRowHeight(i, 22); ui->tableView->setMinimumSize(QSize(ui->tableView->minimumWidth(), driverLapHistoryModel->rowCount() * 22)); } } void DriverDataWidget::printDriverChart(int id) { if (id <= 0) return; DriverData *driverData = eventData.getDriverDataByIdPtr(id); QList<double> pos; for (int i = 0; i < driverData->getPositionHistory().size(); ++i) { int iPos = driverData->getPositionHistory()[i]; if (i > 0 && iPos == 0) iPos = driverData->getPositionHistory()[i-1]; pos.append((double)(iPos)); } posChart->setData(driverData); posChart->repaint(); lapTimeChart->setData(driverData); lapTimeChart->repaint(); // if (eventData.eventType == LTPackets::RACE_EVENT) { gapChart->setData(driverData); gapChart->repaint(); } // else { // ui->chartsTableWidget->insertRow(4); // ui->chartsTableWidget->setRowHeight(4, 20); // item = new QTableWidgetItem("Gap to leader chart"); // item->setTextAlignment(Qt::AlignCenter); // ui->chartsTableWidget->setItem(4, 0, item); // ui->chartsTableWidget->insertRow(5); // ui->chartsTableWidget->setCellWidget(5, 0, gapChart); // ui->chartsTableWidget->setRowHeight(4, 0); // ui->chartsTableWidget->setRowHeight(5, 0); } } void DriverDataWidget::printDriverRecords(int id) { if (id <= 0) return; DriverData *driverData = eventData.getDriverDataByIdPtr(id); Track *tr = 0; TrackWeekendRecords *twr = 0; TrackVersion *tv = 0; TrackRecords::getInstance().gatherSessionRecords(true); TrackRecords::getInstance().getCurrentTrackRecords(&tr, &twr, &tv); ui->s1BLabel->clear(); ui->s2BLabel->clear(); ui->s3BLabel->clear(); ui->tBLabel->clear(); ui->s1RLabel->clear(); ui->s2RLabel->clear(); ui->s3RLabel->clear(); ui->tRLabel->clear(); if (twr != 0 && tv != 0) { QPalette palette; palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); Record rec[4]; rec[0] = tv->getTrackWeekendRecords(eventData.getEventInfo().fpDate.year()).sessionRecords[S1_RECORD]; if (rec[0].time.isValid()) ui->s1BLabel->setText(rec[0].time.toString() + QString(" (%1) ").arg(SeasonData::getInstance().getDriverShortName(rec[0].driver))); rec[1] = tv->getTrackWeekendRecords(eventData.getEventInfo().fpDate.year()).sessionRecords[S2_RECORD]; if (rec[1].time.isValid()) ui->s2BLabel->setText(rec[1].time.toString() + QString(" (%1) ").arg(SeasonData::getInstance().getDriverShortName(rec[1].driver))); rec[2] = tv->getTrackWeekendRecords(eventData.getEventInfo().fpDate.year()).sessionRecords[S3_RECORD]; if (rec[2].time.isValid()) ui->s3BLabel->setText(rec[2].time.toString() + QString(" (%1) ").arg(SeasonData::getInstance().getDriverShortName(rec[2].driver))); rec[3] = tv->getTrackWeekendRecords(eventData.getEventInfo().fpDate.year()).sessionRecords[TIME_RECORD]; if (rec[3].time.isValid()) ui->tBLabel->setText(rec[3].time.toString() + QString(" (%1) ").arg(SeasonData::getInstance().getDriverShortName(rec[3].driver))); ui->s1BLabel->setPalette(palette); ui->s2BLabel->setPalette(palette); ui->s3BLabel->setPalette(palette); ui->tBLabel->setPalette(palette); DriverWeekendRecords dwr = twr->getDriverRecords(driverData->getDriverName()); Record record; record = dwr.getWeekendRecord(S1_RECORD); if (record.time.isValid()) { ui->s1RLabel->setText(record.time.toString() + QString(" (%1)").arg(record.session)); if (driverData->getDriverName() == rec[0].driver) palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); else palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); ui->s1RLabel->setPalette(palette); } record = dwr.getWeekendRecord(S2_RECORD); if (record.time.isValid()) { ui->s2RLabel->setText(record.time.toString() + QString(" (%1)").arg(record.session)); if (driverData->getDriverName() == rec[1].driver) palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); else palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); ui->s2RLabel->setPalette(palette); } record = dwr.getWeekendRecord(S3_RECORD); if (record.time.isValid()) { ui->s3RLabel->setText(record.time.toString() + QString(" (%1)").arg(record.session)); if (driverData->getDriverName() == rec[2].driver) palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); else palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); ui->s3RLabel->setPalette(palette); } record = dwr.getWeekendRecord(TIME_RECORD); if (record.time.isValid()) { ui->tRLabel->setText(record.time.toString() + QString(" (%1)").arg(record.session)); if (driverData->getDriverName() == rec[3].driver) palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); else palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); ui->tRLabel->setPalette(palette); } } } void DriverDataWidget::printDriverRelatedCommentary(int id) { if (id <= 0) return; int idx = 0; if (id == currentDriver) { QString prevLast; QString text = ui->textEdit->toPlainText(); idx = text.lastIndexOf("\n", -2); if (idx != -1) { prevLast = text.mid(idx+1, text.size() - idx - 2); idx = eventData.getCommentary().lastIndexOf(prevLast, -2, Qt::CaseInsensitive); if (idx != -1) idx += prevLast.size(); } else { ui->textEdit->clear(); idx = 0; } } else ui->textEdit->clear(); DriverData *driverData = eventData.getDriverDataByIdPtr(id); QRegExp searchT(/*"[ ,.?!(]" +*/ SeasonData::getInstance().getDriverLastName(driverData->getDriverName()) + "[ \',.?!);:]", Qt::CaseInsensitive); QString lastEvent; idx = eventData.getCommentary().indexOf(searchT, idx); while (idx != -1) { int beg = eventData.getCommentary().lastIndexOf("\n", idx); int end = eventData.getCommentary().indexOf("\n", idx); QString ev = eventData.getCommentary().mid(beg+1, end-beg-1); if (ev != lastEvent) { lastEvent = ev; ui->textEdit->append(ev + "\n"); } idx = eventData.getCommentary().indexOf(searchT, idx+1); } } void DriverDataWidget::resizeEvent(QResizeEvent *event) { int h = event->size().height() - 110; // int w = ui->chartsTableWidget->viewport()->width();//event->size().width() - 40; // ui->chartsTableWidget->setColumnWidth(0, w); // if (eventData.eventType == LTPackets::RACE_EVENT) { // int div = eventData.eventType == LTPackets::RACE_EVENT ? 3 : 2; // ?int end = eventData.eventType == LTPackets::RACE_EVENT ? ui->chartsTableWidget->rowCount() : ui->chartsTableWidget->rowCount() - 2; for (int i = 1; i < ui->chartsTableWidget->rowCount(); i += 2) { int rH = (h/2 < 150 ? 150 : h/2); ui->chartsTableWidget->setRowHeight(i, rH); } } ui->lapTimeChartTableWidget->setRowHeight(1, h > 150 ? h : 150); // else // { // int rH = (2*h/5 < 150 ? 150 : 2*h/5); // ui->chartsTableWidget->setRowHeight(1, rH); // rH = (3*h/5 < 150 ? 150 : 3*h/5); // ui->chartsTableWidget->setRowHeight(3, rH); // ui->chartsTableWidget->setRowHeight(4, 0); // ui->chartsTableWidget->setRowHeight(5, 0); // } on_tabWidget_currentChanged(ui->tabWidget->currentIndex()); } void DriverDataWidget::on_tabWidget_currentChanged(int index) { int w; switch (index) { case 0: w = ui->tableView->viewport()->width(); if (w < ui->scrollAreaWidgetContents_5->width()/2) w = ui->scrollAreaWidgetContents_5->width() - 10; ui->tableView->setColumnWidth(0, 0.1*w); ui->tableView->setColumnWidth(1, 0.06*w); ui->tableView->setColumnWidth(2, 0.185*w); ui->tableView->setColumnWidth(3, 0.23*w); ui->tableView->setColumnWidth(4, 0.13*w); ui->tableView->setColumnWidth(5, 0.1*w); ui->tableView->setColumnWidth(6, 0.1*w); ui->tableView->setColumnWidth(7, 0.1*w); break; case 1: w = ui->lapTimeChartTableWidget->viewport()->width(); ui->lapTimeChartTableWidget->setColumnWidth(0, w); break; case 2: w = ui->chartsTableWidget->viewport()->width(); ui->chartsTableWidget->setColumnWidth(0, w); break; } } void DriverDataWidget::updateView() { on_tabWidget_currentChanged(ui->tabWidget->currentIndex()); } void DriverDataWidget::setFont(const QFont &font, const QFont &cFont) { ui->infoWidget->setFont(font); ui->tableView->setFont(font); ui->textEdit->setFont(cFont); } int DriverDataWidget::currentIndex() { return ui->tabWidget->currentIndex(); } void DriverDataWidget::setCurrentIndex(int i) { ui->tabWidget->setCurrentIndex(i); } void DriverDataWidget::keyPressEvent(QKeyEvent *event) { if (ui->tabWidget->currentIndex() == 0 && event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier) { QItemSelectionModel * selection = ui->tableView->selectionModel(); QModelIndexList indexes = selection->selectedIndexes(); if(indexes.size() < 1) return; qSort(indexes.begin(), indexes.end()); QModelIndex previous = indexes.first(); indexes.removeFirst(); QString selected_text; QModelIndex current; Q_FOREACH(current, indexes) { QVariant data = ui->tableView->model()->data(previous); QString text = data.toString(); selected_text.append(text); if (current.row() != previous.row()) { selected_text.append(QLatin1Char('\n')); } else { selected_text.append(QLatin1Char('\t')); } previous = current; } selected_text.append(ui->tableView->model()->data(current).toString()); selected_text.append(QLatin1Char('\n')); qApp->clipboard()->setText(selected_text); } } void DriverDataWidget::clearData() { ui->textEdit->clear(); ui->carImageLabel->clear(); ui->driverInfoLabel->clear(); ui->gridLabel->setText("Grid position"); ui->gridPositionLabel->clear(); ui->gapLabel->clear(); ui->lastLapLabel->clear(); ui->bestLapLabel->clear(); ui->approxLapLabel->clear(); ui->numPitsLabel->clear(); ui->pitStopsLabel->setText("Pit stops:"); QPalette palette = ui->pitStopsLabel->palette(); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); ui->pitStopsLabel->setPalette(palette); gapChart->clearData(); posChart->clearData(); lapTimeChart->clearData(); driverLapHistoryModel->clear(); ui->tableView->setModel(0); currentDriver = 0; ui->tableView->setModel(driverLapHistoryModel); }
zywhlc-f1lt
src/main_gui/driverdatawidget.cpp
C++
gpl3
22,664
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef PREFERENCESDIALOG_H #define PREFERENCESDIALOG_H #include <QDialog> #include <QNetworkProxy> #include <QSettings> #include <QToolButton> #include "drivercolorsdialog.h" namespace Ui { class PreferencesDialog; } class PreferencesDialog : public QDialog { Q_OBJECT public: explicit PreferencesDialog(QWidget *parent = 0); ~PreferencesDialog(); void setFonts(const QFont &f1, const QFont &f2); void setMainFont(const QFont &f); void setCommentaryFont(const QFont &f); QFont getMainFont() { return mainFont; } QFont getCommentaryFont() { return commentaryFont; } void setSplitterOpaqueResize(bool); bool isSplitterOpaqueResize(); void setDrawCarThumbnails(bool); bool drawCarThumbnails(); void setAutoRecord(bool); bool isAutoRecord(); void setAutoStopRecord(int); int getAutoStopRecord(); void setAutoSaveRecord(int); int getAutoSaveRecord(); void setAutoConnect(bool); bool isAutoConnect(); bool drawTrackerClassification(); void setDrawTrackerClassification(bool); void setCheckForUpdatesEnabled(bool); bool isCheckForUpdatesEnabled(); QNetworkProxy getProxy(); bool proxyEnabled(); signals: void driversColorsChanged(); public slots: int exec(QSettings *); private slots: void on_buttonBox_accepted(); void on_mainFontButton_clicked(); void on_commentaryFontButton_clicked(); void on_autoStopRecordBox_toggled(bool checked); void on_proxyCheckBox_toggled(bool checked); void on_pushButton_clicked(); void on_colorWhiteButton_clicked(); void on_colorCyanButton_clicked(); void on_colorYellowButton_clicked(); void on_colorRedButton_clicked(); void on_colorGreenButton_clicked(); void on_colorVioletButton_clicked(); void on_pushButton_2_clicked(); void on_pushButton_3_clicked(); void on_pushButton_4_clicked(); void on_pushButton_5_clicked(); void on_pushButton_6_clicked(); void on_pushButton_7_clicked(); void on_pushButton_8_clicked(); void on_autoSaveRecordBox_toggled(bool checked); private: void setButtonColor(QToolButton *button, QColor color); Ui::PreferencesDialog *ui; QFont mainFont; QFont commentaryFont; QSettings *settings; QList<QColor> colors; DriverColorsDialog *dcDialog; }; #endif // PREFERENCESDIALOG_H
zywhlc-f1lt
src/main_gui/preferencesdialog.h
C++
gpl3
3,948
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef WEATHERCHARTSWIDGET_H #define WEATHERCHARTSWIDGET_H #include <QtGui/QWidget> #include "ui_weatherchartswidget.h" #include "../charts/weatherchart.h" #include "tools/driverradar.h" class WeatherChartsWidget : public QWidget { Q_OBJECT public: WeatherChartsWidget(QWidget *parent = 0); ~WeatherChartsWidget(); void updateCharts(); private: Ui::WeatherChartsWidgetClass ui; TempChart *tempWidget; WeatherChart *windWidget; WeatherChart *pressureWidget; WeatherChart *humidityWidget; WetDryChart *wetDryWidget; }; #endif // WEATHERCHARTSWIDGET_H
zywhlc-f1lt
src/main_gui/weatherchartswidget.h
C++
gpl3
2,141
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef DRIVERDATAWIDGET_H #define DRIVERDATAWIDGET_H #include <QWidget> #include <QKeyEvent> #include <QPixmap> #include <QLabel> #include <QTableWidgetItem> #include "../core/seasondata.h" #include "../charts/driverdatachart.h" #include "../net/packetparser.h" #include "models/driverlaphistorymodel.h" namespace Ui { class DriverDataWidget; } class DriverDataWidget : public QWidget { Q_OBJECT public: explicit DriverDataWidget(QWidget *parent = 0); ~DriverDataWidget(); void setFont(const QFont &, const QFont &); void updateView(); int currentIndex(); void setCurrentIndex(int); void clearData(); public slots: void updateDriverData(int id) { if (id == currentDriver) printDriverData(currentDriver); } void updateDriverData(const DataUpdates &dataUpdates) { if (dataUpdates.driverIds.contains(currentDriver)) printDriverData(currentDriver); } void printDriverData(int id); void printDriverChart(int id); void printDriverRecords(int id); void printDriverRelatedCommentary(int id); void updateDriverInfo(const DriverData &); protected: void resizeEvent(QResizeEvent *); void keyPressEvent(QKeyEvent *); private slots: void on_tabWidget_currentChanged(int index); private: Ui::DriverDataWidget *ui; DriverDataChart *posChart; LapTimeChart *lapTimeChart; GapChart *gapChart; int currentDriver; EventData &eventData; DriverLapHistoryModel *driverLapHistoryModel; }; #endif // DRIVERDATAWIDGET_H
zywhlc-f1lt
src/main_gui/driverdatawidget.h
C++
gpl3
3,138
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef COMMENTARYWIDGET_H #define COMMENTARYWIDGET_H #include <QSettings> #include <QWidget> namespace Ui { class CommentaryWidget; } class CommentaryWidget : public QWidget { Q_OBJECT public: explicit CommentaryWidget(QWidget *parent = 0); ~CommentaryWidget(); void saveSettings(QSettings &settings); void loadSettings(QSettings &settings); void setFont(const QFont &font); QString getCommentary(); void clear(); public slots: void update(); private: Ui::CommentaryWidget *ui; }; #endif // COMMENTARYWIDGET_H
zywhlc-f1lt
src/main_gui/commentarywidget.h
C++
gpl3
2,110
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "weatherchartswidget.h" #include "../core/colorsmanager.h" #include <QDebug> WeatherChartsWidget::WeatherChartsWidget(QWidget *parent) : QWidget(parent) { ui.setupUi(this); ColorsManager &sd = ColorsManager::getInstance(); tempWidget = new TempChart(sd.getColor(LTPackets::VIOLET), sd.getColor(LTPackets::YELLOW), 0, 1, 5, this); windWidget = new WeatherChart(sd.getColor(LTPackets::GREEN), 2, 5, this); pressureWidget = new WeatherChart(sd.getColor(LTPackets::WHITE), 3, 5, this); pressureWidget->setAllowedMin(900); humidityWidget = new WeatherChart(sd.getColor(LTPackets::RED), 4, 5, this); wetDryWidget = new WetDryChart(sd.getColor(LTPackets::CYAN), 5, 5, this); ui.tempLayout->addWidget(tempWidget); ui.windLayout->addWidget(windWidget); ui.pressureLayout->addWidget(pressureWidget); ui.humidityLayout->addWidget(humidityWidget); ui.wetDryLayout->addWidget(wetDryWidget); } WeatherChartsWidget::~WeatherChartsWidget() { } void WeatherChartsWidget::updateCharts() { switch (ui.tabWidget->currentIndex()) { case 0: tempWidget->repaint(); break; case 1: windWidget->repaint(); break; case 2: pressureWidget->repaint(); break; case 3: humidityWidget->repaint(); break; case 4: wetDryWidget->repaint(); break; } }
zywhlc-f1lt
src/main_gui/weatherchartswidget.cpp
C++
gpl3
2,824
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef DRIVERINFOLABEL_H #define DRIVERINFOLABEL_H #include <QWidget> #include "../core/eventdata.h" class DriverInfoLabel : public QWidget { Q_OBJECT public: explicit DriverInfoLabel(QWidget *parent = 0); QSize sizeHint(); QSize minimumSize(); signals: public slots: void setDriver(const DriverData *dd) { driverData = dd; } void update(); void clear() { driverData = 0; } protected: void paintEvent(QPaintEvent *); private: const DriverData *driverData; QPixmap backgroundPixmap; }; #endif // DRIVERINFOLABEL_H
zywhlc-f1lt
src/main_gui/driverinfolabel.h
C++
gpl3
2,150
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "nosessionboardwidget.h" #include "../core/seasondata.h" #include <QDateTime> NoSessionBoardWidget::NoSessionBoardWidget(QWidget *parent) : QWidget(parent) { ui.setupUi(this); } NoSessionBoardWidget::~NoSessionBoardWidget() { } void NoSessionBoardWidget::showSessionBoard(QString msg) { ui.noSessionWidget->setVisible(true); ui.startupWidget->setVisible(false); int year = 2000 + msg.left(2).toInt(); int month = msg.mid(2, 2).toInt(); int day = msg.mid(4, 2).toInt(); int hour = msg.mid(6, 2).toInt() + 1; QDateTime dateTime(QDate(year, month, day), QTime(hour, 0), Qt::UTC); dateTime = dateTime.toLocalTime(); LTEvent event = SeasonData::getInstance().getCurrentEvent(); QString str = event.eventName + "\n\n" + dateTime.toString("hh:mm, dddd dd MMMM yyyy"); /*QString::number(year) + "." + (month < 10 ? "0" + QString::number(month) : QString::number(month)) + "." + (day < 10 ? "0" + QString::number(day) : QString::number(day)) + " - " + QString::number(hour) + ":00 GMT";*/ ui.sessionLabel->setText(str); QPixmap pix = event.trackImg.height() > 600 ? event.trackImg.scaledToHeight(600, Qt::SmoothTransformation) : event.trackImg; ui.trackMapLabel->setPixmap(pix); } void NoSessionBoardWidget::showStartupBoard() { ui.noSessionWidget->setVisible(false); ui.startupWidget->setVisible(true); LTEvent event = SeasonData::getInstance().getNextEvent(); QString str = event.eventName; str += "\n(" + event.fpDate.toString("dd-MM-yyyy") + " - " + event.raceDate.toString("dd-MM-yyyy") + ")"; ui.sessionLabel2->setText(str); QPixmap pix = event.trackImg.height() > 600 ? event.trackImg.scaledToHeight(600, Qt::SmoothTransformation) : event.trackImg; ui.trackMapLabel->setPixmap(pix); ui.versionLabel->setText("F1LT " + F1LTCore::programVersion()); } void NoSessionBoardWidget::mousePressEvent(QMouseEvent *ev) { if ((ev->pos().x() >= ui.connectLabel->x()) && (ev->pos().x() < (ui.connectLabel->width() + ui.connectLabel->x())) && (ev->pos().y() >= ui.connectLabel->y()) && (ev->pos().y() <= (ui.connectLabel->y() + ui.connectLabel->height()))) emit connectClicked(); if ((ev->pos().x() >= ui.openLabel->x()) && (ev->pos().x() < (ui.openLabel->width() + ui.openLabel->x())) && (ev->pos().y() >= ui.openLabel->y()) && (ev->pos().y() <= (ui.openLabel->y() + ui.openLabel->height()))) emit playClicked(); if ((ev->pos().x() >= ui.loadLabel->x()) && (ev->pos().x() < (ui.loadLabel->width() + ui.loadLabel->x())) && (ev->pos().y() >= ui.loadLabel->y()) && (ev->pos().y() <= (ui.loadLabel->y() + ui.loadLabel->height()))) emit loadClicked(); QWidget::mousePressEvent(ev); }
zywhlc-f1lt
src/main_gui/nosessionboardwidget.cpp
C++
gpl3
4,342
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "sessiondatawidget.h" #include "ui_sessiondatawidget.h" #include <QClipboard> #include <QDebug> #include <QLabel> #include <QPair> #include <QResizeEvent> #include "ltitemdelegate.h" #include "../core/colorsmanager.h" #include "../core/trackrecords.h" SessionDataWidget::SessionDataWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SessionDataWidget), eventData(EventData::getInstance()) { ui->setupUi(this); ui->speedRecordsTable->setModel(&speedRecordsModel); ui->fastestLapsTable->setModel(&fastestLapsModel); ui->pitStopsTable->setModel(&pitStopsModel); ui->speedRecordsTable->setItemDelegate(new LTItemDelegate(this)); ui->fastestLapsTable->setItemDelegate(new LTItemDelegate(this)); ui->pitStopsTable->setItemDelegate(new LTItemDelegate(this)); for (int i = 0; i < speedRecordsModel.rowCount(); ++i) ui->speedRecordsTable->setRowHeight(i, 22); for (int i = 0; i < fastestLapsModel.rowCount(); ++i) ui->fastestLapsTable->setRowHeight(i, 22); for (int i = 0; i < pitStopsModel.rowCount(); ++i) ui->pitStopsTable->setRowHeight(i, 22); setupContents(); } SessionDataWidget::~SessionDataWidget() { delete ui; } QTableWidgetItem* SessionDataWidget::setItem(QTableWidget *table, int row, int col, QString text, Qt::ItemFlags flags, int align, QColor textColor, QBrush background) { QTableWidgetItem *item = table->item(row, col); if (!item) { item = new QTableWidgetItem(text); item->setFlags(flags); table->setItem(row, col, item); } item->setTextAlignment(align); item->setBackground(background); item->setText(text); item->setTextColor(textColor); return item; } void SessionDataWidget::setupContents() { on_tabWidget_currentChanged(ui->tabWidget->currentIndex()); } void SessionDataWidget::updateData(const DataUpdates &dataUpdates) { on_tabWidget_currentChanged(ui->tabWidget->currentIndex()); updateFastestLaps(); switch (ui->tabWidget->currentIndex()) { case 0: updateEventInfo(); case 2: if (dataUpdates.speedRecordsUpdate) updateSpeedRecords(); break; // case 1: // updateFastestLaps(carId); // break; case 3: if (dataUpdates.pitStopsUpdate) updatePitStops(); break; } } void SessionDataWidget::updateEventInfo() { if (eventData.getEventInfo().eventNo < 1) return; LTEvent event = eventData.getEventInfo(); if (event != currentEvent) currentEvent = event; else return; QPalette palette; ui->eventNameLabel->setText(event.eventName); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->eventNameLabel->setPalette(palette); ui->eventPlaceLabel->setText(event.eventPlace); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); ui->eventPlaceLabel->setPalette(palette); ui->eventDateLabel->setText(event.fpDate.toString("dd.MM.yyyy") + " - " + event.raceDate.toString("dd.MM.yyyy")); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->eventDateLabel->setPalette(palette); ui->eventLapsLabel->setText(QString::number(event.laps) + " laps"); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::CYAN)); ui->eventLapsLabel->setPalette(palette); resizeTrackMap(); Track *track = 0; TrackVersion *tv = 0; TrackWeekendRecords *twr = 0; TrackRecords::getInstance().getCurrentTrackRecords(&track, &twr, &tv); if (tv != 0) { ui->qRTLabel->setText(tv->trackRecords[QUALI_RECORD].time.toString()); ui->qRDLabel->setText(tv->trackRecords[QUALI_RECORD].driver); ui->qRDTLabel->setText(tv->trackRecords[QUALI_RECORD].team); ui->qRYLabel->setText(tv->trackRecords[QUALI_RECORD].year); ui->rRTLabel->setText(tv->trackRecords[RACE_RECORD].time.toString()); ui->rRDLabel->setText(tv->trackRecords[RACE_RECORD].driver); ui->rRDTLabel->setText(tv->trackRecords[RACE_RECORD].team); ui->rRYLabel->setText(tv->trackRecords[RACE_RECORD].year); QPalette palette; palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); ui->qRTLabel->setPalette(palette); ui->rRTLabel->setPalette(palette); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->qRDLabel->setPalette(palette); ui->qRDTLabel->setPalette(palette); ui->rRDLabel->setPalette(palette); ui->rRDTLabel->setPalette(palette); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->qRYLabel->setPalette(palette); ui->rRYLabel->setPalette(palette); } else { ui->qRTLabel->clear(); ui->qRDLabel->clear(); ui->qRDTLabel->clear(); ui->qRYLabel->clear(); ui->rRTLabel->clear(); ui->rRDLabel->clear(); ui->rRDTLabel->clear(); ui->rRYLabel->clear(); } // QTableWidgetItem *item; // // item = setItem(ui->tableWidget_5, 0, 0, event.eventName, Qt::NoItemFlags, Qt::AlignCenter, SeasonData::getInstance().getColor(LTPackets::YELLOW)); // item->setFont(QFont("Arial", 15, QFont::Bold)); // item = setItem(ui->tableWidget_5, 1, 0, event.eventPlace, Qt::NoItemFlags, Qt::AlignCenter, SeasonData::getInstance().getColor(LTPackets::GREEN)); // item->setFont(QFont("Arial", 12, QFont::Bold)); // item = setItem(ui->tableWidget_5, 2, 0, event.fpDate.toString("dd.MM.yyyy") + " - " + event.raceDate.toString("dd.MM.yyyy"), // Qt::NoItemFlags, Qt::AlignCenter, SeasonData::getInstance().getColor(LTPackets::WHITE)); // item->setFont(QFont("Arial", 10, QFont::Bold)); // item = setItem(ui->tableWidget_5, 3, 0, QString::number(event.laps) + " laps", Qt::NoItemFlags, Qt::AlignCenter, SeasonData::getInstance().getColor(LTPackets::CYAN)); // QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget_5->cellWidget(4, 0)); // if (!lab) // { // lab = new QLabel(this); // ui->tableWidget_5->setCellWidget(4, 0, lab); // } //// if (!lab->pixmap()) // { // QPixmap trackImg = eventData.getEventInfo().trackImg; // if (!trackImg.isNull()) // { // QPixmap pix = trackImg; // int w = width() - 20; // int h = height() - 20; // if (pix.width() > w) // pix = trackImg.scaledToWidth(w, Qt::SmoothTransformation); // if (pix.height() > h) // pix = trackImg.scaledToHeight(h, Qt::SmoothTransformation); // lab->setPixmap(pix); //// lab->resize(trackImg.size()); // lab->setAlignment(Qt::AlignCenter); // if (ui->tableWidget_5->rowHeight(4) < trackImg.height()) // ui->tableWidget_5->setRowHeight(4,trackImg.height()); // ui->tableWidget_5->setColumnWidth(0, trackImg.width()); // } // } } void SessionDataWidget::resizeTrackMap() { QPixmap trackImg = currentEvent.trackImg; if (!trackImg.isNull()) { QPixmap pix = trackImg; int w = ui->scrollArea_2->width() - 20; int h = ui->scrollArea_2->height() - 20; if (pix.width() > w) pix = trackImg.scaledToWidth(w, Qt::SmoothTransformation); if (pix.height() > h) pix = trackImg.scaledToHeight(h, Qt::SmoothTransformation); ui->eventMapLabel->setPixmap(pix); } } void SessionDataWidget::updateSpeedRecords() { speedRecordsModel.update(); } void SessionDataWidget::updateFastestLaps() { fastestLapsModel.update(); ui->fastestLapsTable->setMinimumSize(QSize(ui->fastestLapsTable->minimumWidth(), fastestLapsModel.rowCount() * 22)); QPalette palette; palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); QList<LapData> fastestLaps = fastestLapsModel.getFastestLaps(); QString str = eventData.getSessionRecords().getFastestLap().getTime(); if (eventData.getEventType() != LTPackets::RACE_EVENT && !fastestLaps.isEmpty()) str = fastestLaps[0].getTime().toString(); ui->flTimeLabel->setText(str); ui->flTimeLabel->setPalette(palette); str = eventData.getSessionRecords().getFastestLap().getDriverName(); if (eventData.getEventType() != LTPackets::RACE_EVENT && !fastestLaps.isEmpty() && fastestLaps[0].getCarID() != -1) { DriverData *dd = eventData.getDriverDataByIdPtr(fastestLaps[0].getCarID()); if (dd != 0) str = dd->getDriverName(); } ui->flDriverLabel->setText(str); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->flDriverLabel->setPalette(palette); str = QString("L%1").arg(eventData.getSessionRecords().getFastestLap().getLapNumber()); if (eventData.getSessionRecords().getFastestLap().getLapNumber() <= 0) str = ""; if (eventData.getEventType() == LTPackets::PRACTICE_EVENT && !fastestLaps.isEmpty() && fastestLaps[0].getTime().isValid()) str = SeasonData::getInstance().getSessionDefaults().correctFPTime(fastestLaps[0].getPracticeLapExtraData().getSessionTime()).toString("h:mm:ss"); else if (eventData.getEventType() == LTPackets::QUALI_EVENT && !fastestLaps.isEmpty() && fastestLaps[0].getTime().isValid()) { QString time = SeasonData::getInstance().getSessionDefaults().correctQualiTime(fastestLaps[0].getQualiLapExtraData().getSessionTime(), fastestLaps[0].getQualiLapExtraData().getQualiPeriod()).toString("mm:ss"); str = QString("%1 (Q%2)").arg(time).arg(fastestLaps[0].getQualiLapExtraData().getQualiPeriod()); } ui->flLapLabel->setText(str); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->flLapLabel->setPalette(palette); ui->s1TimeLabel->setText(eventData.getSessionRecords().getSectorRecord(1).getTime()); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); ui->s1TimeLabel->setPalette(palette); ui->s1DriverLabel->setText(eventData.getSessionRecords().getSectorRecord(1).getDriverName()); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->s1DriverLabel->setPalette(palette); str = ""; if ((eventData.getEventType() == LTPackets::RACE_EVENT && eventData.getSessionRecords().getSectorRecord(1).getLapNumber() > -1)) str = QString("L%1").arg(eventData.getSessionRecords().getSectorRecord(1).getLapNumber()); else if (eventData.getSessionRecords().getSectorRecord(1).getSessionTime().isValid()) { if (eventData.getEventType() == LTPackets::PRACTICE_EVENT) str = SeasonData::getInstance().getSessionDefaults().correctFPTime(eventData.getSessionRecords().getSectorRecord(1).getSessionTime()).toString("h:mm:ss"); else { QString time = SeasonData::getInstance().getSessionDefaults().correctQualiTime(eventData.getSessionRecords().getSectorRecord(1).getSessionTime(), eventData.getSessionRecords().getSectorRecord(1).getQualiPeriod()).toString("mm:ss"); str = QString("%1 (Q%2)").arg(time).arg(eventData.getSessionRecords().getSectorRecord(1).getQualiPeriod()); } } ui->s1LapLabel->setText(str); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->s1LapLabel->setPalette(palette); ui->s2TimeLabel->setText(eventData.getSessionRecords().getSectorRecord(2).getTime()); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); ui->s2TimeLabel->setPalette(palette); ui->s2DriverLabel->setText(eventData.getSessionRecords().getSectorRecord(2).getDriverName()); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->s2DriverLabel->setPalette(palette); str = ""; if ((eventData.getEventType() == LTPackets::RACE_EVENT && eventData.getSessionRecords().getSectorRecord(2).getLapNumber() > -1)) str = QString("L%1").arg(eventData.getSessionRecords().getSectorRecord(2).getLapNumber()); else if (eventData.getSessionRecords().getSectorRecord(2).getSessionTime().isValid()) { if (eventData.getEventType() == LTPackets::PRACTICE_EVENT) str = SeasonData::getInstance().getSessionDefaults().correctFPTime(eventData.getSessionRecords().getSectorRecord(2).getSessionTime()).toString("h:mm:ss"); else { QString time = SeasonData::getInstance().getSessionDefaults().correctQualiTime(eventData.getSessionRecords().getSectorRecord(2).getSessionTime(), eventData.getSessionRecords().getSectorRecord(2).getQualiPeriod()).toString("mm:ss"); str = QString("%1 (Q%2)").arg(time).arg(eventData.getSessionRecords().getSectorRecord(2).getQualiPeriod()); } } ui->s2LapLabel->setText(str); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->s2LapLabel->setPalette(palette); ui->s3TimeLabel->setText(eventData.getSessionRecords().getSectorRecord(3).getTime()); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); ui->s3TimeLabel->setPalette(palette); ui->s3DriverLabel->setText(eventData.getSessionRecords().getSectorRecord(3).getDriverName()); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->s3DriverLabel->setPalette(palette); str = ""; if ((eventData.getEventType() == LTPackets::RACE_EVENT && eventData.getSessionRecords().getSectorRecord(3).getLapNumber() > -1)) str = QString("L%1").arg(eventData.getSessionRecords().getSectorRecord(3).getLapNumber()); else if (eventData.getSessionRecords().getSectorRecord(3).getSessionTime().isValid()) { if (eventData.getEventType() == LTPackets::PRACTICE_EVENT) str = SeasonData::getInstance().getSessionDefaults().correctFPTime(eventData.getSessionRecords().getSectorRecord(3).getSessionTime()).toString("h:mm:ss"); else { QString time = SeasonData::getInstance().getSessionDefaults().correctQualiTime(eventData.getSessionRecords().getSectorRecord(3).getSessionTime(), eventData.getSessionRecords().getSectorRecord(3).getQualiPeriod()).toString("mm:ss"); str = QString("%1 (Q%2)").arg(time).arg(eventData.getSessionRecords().getSectorRecord(3).getQualiPeriod()); } } ui->s3LapLabel->setText(str); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->s3LapLabel->setPalette(palette); QString tL = ""; if (eventData.getSessionRecords().getSectorRecord(1).getTime().toString() != "" && eventData.getSessionRecords().getSectorRecord(2).getTime().toString() != "" && eventData.getSessionRecords().getSectorRecord(3).getTime().toString() != "") tL = LapData::sumSectors(eventData.getSessionRecords().getSectorRecord(1).getTime(), eventData.getSessionRecords().getSectorRecord(2).getTime(), eventData.getSessionRecords().getSectorRecord(3).getTime()); ui->theoreticalTimeLabel->setText(tL); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::CYAN)); ui->theoreticalTimeLabel->setPalette(palette); } void SessionDataWidget::updatePitStops(bool clear) { if (clear) { } pitStopsModel.update(); for (int i = 0; i < pitStopsModel.rowCount(); ++i) ui->pitStopsTable->setRowHeight(i, 22); } void SessionDataWidget::on_tabWidget_currentChanged(int index) { if (ui->eventMapLabel->pixmap()) { if (ui->eventMapLabel->pixmap()->width() < 10) { resizeTrackMap(); } } int w; switch (index) { case 0: // updateSpeedRecords(eventData); updateEventInfo(); break; case 1: w = ui->fastestLapsTable->viewport()->width(); ui->fastestLapsTable->setColumnWidth(0, 0.06 * w); ui->fastestLapsTable->setColumnWidth(1, 0.28 * w); ui->fastestLapsTable->setColumnWidth(2, 0.16 * w); ui->fastestLapsTable->setColumnWidth(3, 0.11 * w); ui->fastestLapsTable->setColumnWidth(4, 0.09 * w); ui->fastestLapsTable->setColumnWidth(5, 0.09 * w); ui->fastestLapsTable->setColumnWidth(6, 0.09 * w); ui->fastestLapsTable->setColumnWidth(7, 0.12 * w); break; case 2: // updatePitStops(eventData); updateSpeedRecords(); w = ui->speedRecordsTable->viewport()->width(); ui->speedRecordsTable->setColumnWidth(0, 0.34 * w); ui->speedRecordsTable->setColumnWidth(1, 0.11 * w); ui->speedRecordsTable->setColumnWidth(2, 0.09 * w); ui->speedRecordsTable->setColumnWidth(3, 0.34 * w); ui->speedRecordsTable->setColumnWidth(4, 0.11 * w); break; case 3: updatePitStops(); w = ui->pitStopsTable->viewport()->width(); ui->pitStopsTable->setColumnWidth(0, 0.1 * w); ui->pitStopsTable->setColumnWidth(1, 0.1 * w); ui->pitStopsTable->setColumnWidth(2, 0.1 * w); ui->pitStopsTable->setColumnWidth(3, 0.35 * w); ui->pitStopsTable->setColumnWidth(4, 0.2 * w); ui->pitStopsTable->setColumnWidth(5, 0.15 * w); default: break; } } void SessionDataWidget::resizeEvent(QResizeEvent *) { on_tabWidget_currentChanged(ui->tabWidget->currentIndex()); if (ui->tabWidget->currentIndex() == 0) resizeTrackMap(); } void SessionDataWidget::setFont(const QFont &font) { ui->speedRecordsTable->setFont(font); ui->fastestLapsTable->setFont(font); ui->pitStopsTable->setFont(font); ui->infoWidget->setFont(font); ui->recordsLabel->setFont(font); for (int i = 0; i < ui->recordsLayout->count(); ++i) ui->recordsLayout->itemAt(i)->widget()->setFont(font); } int SessionDataWidget::currentIndex() { return ui->tabWidget->currentIndex(); } void SessionDataWidget::setCurrentIndex(int i) { ui->tabWidget->setCurrentIndex(i); } void SessionDataWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier) { QTableView *tWidget; if (ui->tabWidget->currentIndex() == 1) tWidget = ui->fastestLapsTable; else if (ui->tabWidget->currentIndex() == 2) tWidget = ui->speedRecordsTable; else if (ui->tabWidget->currentIndex() == 3) tWidget = ui->pitStopsTable; else return; QItemSelectionModel * selection = tWidget->selectionModel(); QModelIndexList indexes = selection->selectedIndexes(); if(indexes.size() < 1) return; // QModelIndex::operator < sorts first by row, then by column. // this is what we need qSort(indexes.begin(), indexes.end()); // You need a pair of indexes to find the row changes QModelIndex previous = indexes.first(); indexes.removeFirst(); QString selected_text; QModelIndex current; Q_FOREACH(current, indexes) { QVariant data = tWidget->model()->data(previous); QString text = data.toString(); // At this point `text` contains the text in one cell selected_text.append(text); // If you are at the start of the row the row number of the previous index // isn't the same. Text is followed by a row separator, which is a newline. if (current.row() != previous.row()) { selected_text.append(QLatin1Char('\n')); } // Otherwise it's the same row, so append a column separator, which is a tab. else { selected_text.append(QLatin1Char('\t')); } previous = current; } selected_text.append(tWidget->model()->data(current).toString()); selected_text.append(QLatin1Char('\n')); qApp->clipboard()->setText(selected_text); } } void SessionDataWidget::clearData() { setupContents(); } void SessionDataWidget::clearFastestLaps() { }
zywhlc-f1lt
src/main_gui/sessiondatawidget.cpp
C++
gpl3
22,691
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef DRIVERCOLORSDIALOG_H #define DRIVERCOLORSDIALOG_H #include <QDialog> #include <QToolButton> namespace Ui { class DriverColorsDialog; } class DriverColorsDialog : public QDialog { Q_OBJECT public: explicit DriverColorsDialog(QWidget *parent = 0); ~DriverColorsDialog(); int exec(); public slots: void onColorButtonClicked(); void onResetButtonClicked(); private slots: void on_buttonBox_accepted(); void on_pushButton_clicked(); private: void setButtonColor(QToolButton *button, QColor color); Ui::DriverColorsDialog *ui; QList<QColor> colors; }; #endif // DRIVERCOLORSDIALOG_H
zywhlc-f1lt
src/main_gui/drivercolorsdialog.h
C++
gpl3
2,190
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "drivercolorsdialog.h" #include "ui_drivercolorsdialog.h" #include <QColorDialog> #include <QDebug> #include <QLabel> #include <QToolButton> #include "../core/colorsmanager.h" #include "../core/eventdata.h" DriverColorsDialog::DriverColorsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::DriverColorsDialog) { ui->setupUi(this); } DriverColorsDialog::~DriverColorsDialog() { delete ui; } int DriverColorsDialog::exec() { SeasonData &sd = SeasonData::getInstance(); colors = ColorsManager::getInstance().getDriverColors(); int i = 0; for (; i < sd.getTeams().size(); ++i) { QList<LTDriver> drivers = sd.getMainDrivers(sd.getTeams()[i]); if (drivers.size() != 2) continue; if ((ui->verticalLayout->count()-2) <= i) { QHBoxLayout *layout = new QHBoxLayout(); QLabel *label = new QLabel(this); label->setText(QString("%1 %2").arg(drivers[0].no).arg(drivers[0].name)); label->updateGeometry(); QToolButton *button = new QToolButton(this); button->setMaximumHeight(16); button->setMaximumWidth(16); setButtonColor(button, /*sd.getCarColor(sd.getTeams()[i].driver1No)*/colors[i*2]); layout->addWidget(button); connect(button, SIGNAL(clicked()), this, SLOT(onColorButtonClicked())); button = new QToolButton(this); button->setText("Reset"); button->setMaximumHeight(20); layout->addWidget(button); connect(button, SIGNAL(clicked()), this, SLOT(onResetButtonClicked())); layout->addWidget(label); //colors.append(sd.getCarColor(sd.getTeams()[i].driver1No)); // layout = new QHBoxLayout(this); label = new QLabel(this); label->setText(QString("%1 %2").arg(drivers[1].no).arg(drivers[1].name)); label->updateGeometry(); button = new QToolButton(this); button->setMaximumHeight(16); button->setMaximumWidth(16); setButtonColor(button, /*sd.getCarColor(sd.getTeams()[i].driver2No)*/colors[i*2+1]); layout->addWidget(button); connect(button, SIGNAL(clicked()), this, SLOT(onColorButtonClicked())); button = new QToolButton(this); button->setText("Reset"); button->setMaximumHeight(20); layout->addWidget(button); connect(button, SIGNAL(clicked()), this, SLOT(onResetButtonClicked())); layout->addWidget(label); //colors.append(sd.getCarColor(sd.getTeams()[i].driver2No)); ui->verticalLayout->insertLayout(ui->verticalLayout->count() - 2, layout); } else { QHBoxLayout *layout = static_cast<QHBoxLayout*>(ui->verticalLayout->itemAt(i)->layout()); QLabel *label = static_cast<QLabel*>(layout->itemAt(2)->widget()); QToolButton *button = static_cast<QToolButton*>(layout->itemAt(0)->widget()); label->setText(QString("%1 %2").arg(drivers[0].no).arg(drivers[0].name)); setButtonColor(button, ColorsManager::getInstance().getCarColor(drivers[0].no)); label->setVisible(true); button->setVisible(true); button = static_cast<QToolButton*>(layout->itemAt(1)->widget()); button->setVisible(true); label = static_cast<QLabel*>(layout->itemAt(5)->widget()); button = static_cast<QToolButton*>(layout->itemAt(3)->widget()); label->setText(QString("%1 %2").arg(drivers[1].no).arg(drivers[1].name)); setButtonColor(button, ColorsManager::getInstance().getCarColor(drivers[1].no)); label->setVisible(true); button->setVisible(true); button = static_cast<QToolButton*>(layout->itemAt(4)->widget()); button->setVisible(true); } } for (; i < ui->verticalLayout->count()-2; ++i) { QHBoxLayout *layout = static_cast<QHBoxLayout*>(ui->verticalLayout->itemAt(i)->layout()); QLabel *label = static_cast<QLabel*>(layout->itemAt(2)->widget()); QToolButton *button = static_cast<QToolButton*>(layout->itemAt(0)->widget()); label->setVisible(false); button->setVisible(false); button = static_cast<QToolButton*>(layout->itemAt(1)->widget()); button->setVisible(false); label = static_cast<QLabel*>(layout->itemAt(5)->widget()); button = static_cast<QToolButton*>(layout->itemAt(3)->widget()); label->setVisible(false); button->setVisible(false); button = static_cast<QToolButton*>(layout->itemAt(4)->widget()); button->setVisible(false); } return QDialog::exec(); } void DriverColorsDialog::onColorButtonClicked() { QToolButton *button = static_cast<QToolButton*>(QObject::sender()); for (int i = 0; i < ui->verticalLayout->count()-2; ++i) { QHBoxLayout *layout = static_cast<QHBoxLayout*>(ui->verticalLayout->itemAt(i)->layout()); QToolButton *colorButton = static_cast<QToolButton*>(layout->itemAt(0)->widget()); if (button == colorButton) { QColor color = QColorDialog::getColor(colors[i * 2], this); if (color.isValid()) { setButtonColor(colorButton, color); colors[i * 2] = color; } return; } colorButton = static_cast<QToolButton*>(layout->itemAt(3)->widget()); if (button == colorButton) { QColor color = QColorDialog::getColor(colors[i * 2 + 1], this); if (color.isValid()) { setButtonColor(colorButton, color); colors[i * 2 + 1] = color; } return; } } } void DriverColorsDialog::onResetButtonClicked() { QToolButton *button = static_cast<QToolButton*>(QObject::sender()); for (int i = 0; i < ui->verticalLayout->count()-2; ++i) { QHBoxLayout *layout = static_cast<QHBoxLayout*>(ui->verticalLayout->itemAt(i)->layout()); QToolButton *resetButton = static_cast<QToolButton*>(layout->itemAt(1)->widget()); QToolButton *colorButton = static_cast<QToolButton*>(layout->itemAt(0)->widget()); if (button == resetButton) { setButtonColor(colorButton, ColorsManager::getInstance().getDefaultDriverColors()[i * 2]); colors[i * 2] = ColorsManager::getInstance().getDefaultDriverColors()[i * 2]; return; } resetButton = static_cast<QToolButton*>(layout->itemAt(4)->widget()); colorButton = static_cast<QToolButton*>(layout->itemAt(3)->widget()); if (button == resetButton) { setButtonColor(colorButton, ColorsManager::getInstance().getDefaultDriverColors()[i * 2 + 1]); colors[i * 2 + 1] = ColorsManager::getInstance().getDefaultDriverColors()[i * 2 + 1]; return; } } } void DriverColorsDialog::setButtonColor(QToolButton *button, QColor color) { QString styleSheet = "background-color: rgb(" + QString("%1, %2, %3").arg(color.red()).arg(color.green()).arg(color.blue()) + ");\n "\ "border-style: solid;\n "\ "border-width: 1px;\n "\ "border-radius: 3px;\n "\ "border-color: rgb(153, 153, 153);\n "\ "padding: 3px;\n"; button->setStyleSheet(styleSheet); } void DriverColorsDialog::on_buttonBox_accepted() { ColorsManager::getInstance().setDriverColors(colors); ImagesFactory::getInstance().getHelmetsFactory().reloadHelmets(); } void DriverColorsDialog::on_pushButton_clicked() { for (int i = 0; i < ui->verticalLayout->count()-2; ++i) { QHBoxLayout *layout = static_cast<QHBoxLayout*>(ui->verticalLayout->itemAt(i)->layout()); QToolButton *colorButton = static_cast<QToolButton*>(layout->itemAt(0)->widget()); setButtonColor(colorButton, ColorsManager::getInstance().getDefaultDriverColors()[i * 2]); colors[i * 2] = ColorsManager::getInstance().getDefaultDriverColors()[i * 2]; colorButton = static_cast<QToolButton*>(layout->itemAt(3)->widget()); setButtonColor(colorButton, ColorsManager::getInstance().getDefaultDriverColors()[i * 2 + 1]); colors[i * 2 + 1] = ColorsManager::getInstance().getDefaultDriverColors()[i * 2 + 1]; } }
zywhlc-f1lt
src/main_gui/drivercolorsdialog.cpp
C++
gpl3
10,089
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "updatescheckerdialog.h" #include "ui_updatescheckerdialog.h" #include "../core/f1ltcore.h" #include "../net/networksettings.h" UpdatesCheckerDialog::UpdatesCheckerDialog(QWidget *parent) : QDialog(parent, Qt::Window), ui(new Ui::UpdatesCheckerDialog) { ui->setupUi(this); } UpdatesCheckerDialog::~UpdatesCheckerDialog() { delete ui; } void UpdatesCheckerDialog::checkForUpdates() { req = QNetworkRequest(NetworkSettings::getInstance().getVersionUrl()); req.setRawHeader("User-Agent","f1lt"); if (NetworkSettings::getInstance().usingProxy()) manager.setProxy(NetworkSettings::getInstance().getProxy()); else manager.setProxy(QNetworkProxy::NoProxy); reply = manager.get(req); connect(reply, SIGNAL(finished()), this, SLOT(finished())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); } bool UpdatesCheckerDialog::newVersionIsAvailable(QString version) { QString currVersion = F1LTCore::programVersion(); if (currVersion != version) { QStringList lstOld = currVersion.split("."); QStringList lstNew = version.split("."); for (int i = 0; i < lstOld.size() && i < lstNew.size(); ++i) { int vOld = lstOld[i].toInt(); int vNew = lstNew[i].toInt(); if (vNew > vOld) return true; } } return false; } void UpdatesCheckerDialog::loadSettings(QSettings &settings) { restoreGeometry(settings.value("ui/updatechecker_geometry").toByteArray()); } void UpdatesCheckerDialog::saveSettings(QSettings &settings) { settings.setValue("ui/updatechecker_geometry", saveGeometry()); } void UpdatesCheckerDialog::finished() { QString version = reply->readAll().constData(); if (newVersionIsAvailable(version)) { ui->textEdit->setText("<p align=\"center\"><h1>F1LT new version (" + version + ") is available!</h1></p>"); ui->textEdit->append("<p align=\"center\"><img src=\":/ui_icons/icon.png\"/></p>"); ui->textEdit->append("<p align=\"center\"><h3>You can download it at <a style=\"color:red\" href=\"http://f1lt.pl\">F1LT home site</a>.</h3></p>"); if (!isVisible()) emit newVersionAvailable(); } else { ui->textEdit->setText("<p align=\"center\"><h2>No updates found.</h2></p>"); ui->textEdit->append("<p align=\"center\"><img src=\":/ui_icons/icon.png\"/></p>"); ui->textEdit->append("<p align=\"center\"><h3>You already have the latest F1LT version installed.</h3></p>"); } } void UpdatesCheckerDialog::error(QNetworkReply::NetworkError) { } void UpdatesCheckerDialog::show(bool check) { QDialog::show(); if (check) { ui->textEdit->setText("Checking for updates..."); checkForUpdates(); } } void UpdatesCheckerDialog::on_buttonBox_clicked(QAbstractButton *) { accept(); }
zywhlc-f1lt
src/main_gui/updatescheckerdialog.cpp
C++
gpl3
4,497
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LTWINDOW_H #define LTWINDOW_H #include <QMainWindow> #include <QByteArray> #include <QIcon> #include <QList> #include <QProgressDialog> #include <QSettings> #include "aboutdialog.h" #include "../net/datastreamreader.h" #include "../player/eventplayer.h" #include "../player/eventrecorder.h" #include "../tools/drivertrackerwidget.h" #include "../tools/followadriverdialog.h" #include "../tools/headtoheaddialog.h" #include "../tools/laptimecomparisondialog.h" #include "../tools/ltfilesmanagerdialog.h" #include "../tools/trackrecordsdialog.h" #include "logindialog.h" #include "preferencesdialog.h" #include "../tools/sessionanalysiswidget.h" #include "../tools/sessiontimeswidget.h" #include "../core/sessiontimer.h" #include "delaywidget.h" #include "updatescheckerdialog.h" namespace Ui { class LTWindow; } class LTWindow : public QMainWindow { Q_OBJECT public: explicit LTWindow(QWidget *parent = 0); ~LTWindow(); void loadSettings(); void saveSettings(); void setFonts(const QFont &mainFont, const QFont &commentaryFont); void connectToServer(); void startRecording(bool autoRecord = false); void stopRecording(bool autoStop = false); void setupDialogs(); public slots: bool close(); void eventPlayerOpenFile(QString); void eventPlayerPlayClicked(int); void eventPlayerPauseClicked(); void eventPlayerRewindToStartClicked(); void eventPlayerForwardToEndClicked(); void eventPlayerRewindClicked(); void eventPlayerStopClicked(bool connect = true); void ltWidgetDriverSelected(int id); private slots: void tryAuthorize(); void authorized(QString); void authorizationError(); void error(QAbstractSocket::SocketError); void error(QNetworkReply::NetworkError); void on_actionConnect_triggered(); void eventDataChanged(const DataUpdates &); void driverDataChanged(int, const DataUpdates &); void dataChanged(const DataUpdates &); void sessionStarted(); void showNoSessionBoard(bool, QString); void updateWeather(); void onNewVersionAvailable(); void timeout(); // void on_tableWidget_cellDoubleClicked(int row, int column); // void on_tableWidget_cellClicked(int row, int); void on_tabWidget_currentChanged(int index); void on_actionHead_to_head_triggered(); void on_actionLap_time_comparison_triggered(); void on_actionRecord_triggered(); void on_actionStop_recording_triggered(); void autoStopRecording(); void on_actionPreferences_triggered(); void on_actionAbout_triggered(); void on_actionAbout_Qt_triggered(); void on_actionOpen_triggered(); void showSessionBoard(bool show); void on_actionSession_analysis_triggered(); void on_actionLT_files_data_base_triggered(); void on_actionFollow_a_driver_triggered(); void on_actionSession_times_triggered(); void on_actionDriver_tracker_triggered(); void on_actionTrack_records_triggered(); void on_actionCheck_for_updates_triggered(); private: Ui::LTWindow *ui; DataStreamReader *streamReader; QSettings *settings; QList<HeadToHeadDialog*> h2hDialog; QList<FollowADriverDialog*> fadDialog; QList<LapTimeComparisonDialog*> ltcDialog; int currDriver; SessionTimer *sessionTimer; EventRecorder *eventRecorder; EventPlayer *eventPlayer; QAction *eventPlayerAction; bool recording; bool playing; PreferencesDialog *prefs; LoginDialog *loginDialog; EventData &eventData; SessionAnalysisWidget *saw; SessionTimesWidget *stw; QProgressDialog *connectionProgress; LTFilesManagerDialog *ltFilesManagerDialog; TrackRecordsDialog *trackRecordsDialog; AboutDialog *aboutDialog; DriverTrackerWidget *driverTrackerWidget; DelayWidget *delayWidget; QAction *delayWidgetAction; UpdatesCheckerDialog *updatesCheckerDialog; }; #endif // LTWINDOW_H
zywhlc-f1lt
src/main_gui/ltwindow.h
C++
gpl3
5,496
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "ltwindow.h" #include "ui_ltwindow.h" #include <QDir> #include <QFileDialog> #include <QFileInfo> #include <QMessageBox> #include <QTableWidgetItem> #include "logindialog.h" #include "../net/networksettings.h" LTWindow::LTWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::LTWindow), eventData(EventData::getInstance()) { ui->setupUi(this); currDriver = -1; streamReader = new DataStreamReader(this); prefs = new PreferencesDialog(this); settings = new QSettings(F1LTCore::iniFile(), QSettings::IniFormat, this); loginDialog = new LoginDialog(this); ltFilesManagerDialog = new LTFilesManagerDialog(this); trackRecordsDialog = new TrackRecordsDialog(this); saw = new SessionAnalysisWidget(); stw = new SessionTimesWidget(); driverTrackerWidget = new DriverTrackerWidget(); aboutDialog = new AboutDialog(this); updatesCheckerDialog = new UpdatesCheckerDialog(this); // ui->trackStatusWidget->setupItems(); connect(streamReader, SIGNAL(tryAuthorize()), this, SLOT(tryAuthorize())); connect(streamReader, SIGNAL(authorized(QString)), this, SLOT(authorized(QString))); connect(streamReader, SIGNAL(eventDataChanged(const DataUpdates&)), this, SLOT(eventDataChanged(const DataUpdates&))); connect(streamReader, SIGNAL(driverDataChanged(int, const DataUpdates&)), this, SLOT(driverDataChanged(int, const DataUpdates&))); connect(streamReader, SIGNAL(dataChanged(const DataUpdates&)), this, SLOT(dataChanged(const DataUpdates&))); connect(streamReader, SIGNAL(sessionStarted()), this, SLOT(sessionStarted())); connect(streamReader, SIGNAL(authorizationError()), this, SLOT(authorizationError())); connect(streamReader, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(error(QAbstractSocket::SocketError))); connect(streamReader, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(error(QNetworkReply::NetworkError))); connect(streamReader, SIGNAL(noLiveSession(bool, QString)), this, SLOT(showNoSessionBoard(bool, QString))); connect(updatesCheckerDialog, SIGNAL(newVersionAvailable()), this, SLOT(onNewVersionAvailable())); sessionTimer = new SessionTimer(this); connect(sessionTimer, SIGNAL(updateWeather()), this, SLOT(updateWeather())); connect(&SeasonData::getInstance(), SIGNAL(seasonDataChanged()), &ImagesFactory::getInstance(), SLOT(reloadGraphics())); connect(&SeasonData::getInstance(), SIGNAL(seasonDataChanged()), &ColorsManager::getInstance(), SLOT(calculateDefaultDriverColors())); connect(&SeasonData::getInstance(), SIGNAL(seasonDataChanged()), saw, SLOT(setupColors())); connect(prefs, SIGNAL(driversColorsChanged()), saw, SLOT(setupColors())); eventRecorder = new EventRecorder(sessionTimer, this); eventPlayer = new EventPlayer(this); delayWidget = new DelayWidget(this); connect(delayWidget, SIGNAL(delayChanged(int, int)), streamReader, SLOT(setDelay(int, int))); connect(delayWidget, SIGNAL(delayChanged(int, int)), sessionTimer, SLOT(setDelay(int, int))); connect(sessionTimer, SIGNAL(synchronizingTimer(bool)), delayWidget, SLOT(synchronizingTimer(bool))); connect(sessionTimer, SIGNAL(synchronizingTimer(bool)), driverTrackerWidget, SLOT(pauseTimer(bool))); connect(ui->messageBoardWidget, SIGNAL(connectClicked()), this, SLOT(on_actionConnect_triggered())); connect(ui->messageBoardWidget, SIGNAL(playClicked()), this, SLOT(on_actionOpen_triggered())); connect(ui->messageBoardWidget, SIGNAL(loadClicked()), this, SLOT(on_actionLT_files_data_base_triggered())); loadSettings(); ColorsManager::getInstance().calculateDefaultDriverColors(); saw->setupColors(); delayWidgetAction = ui->mainToolBar->addWidget(delayWidget); delayWidgetAction->setVisible(true); eventPlayerAction = ui->mainToolBar->addWidget(eventPlayer); eventPlayerAction->setVisible(false); recording = false; playing = false; connectionProgress = new QProgressDialog(this); connect(sessionTimer, SIGNAL(timeout()), this, SLOT(timeout())); connect(eventRecorder, SIGNAL(recordingStopped()), this, SLOT(autoStopRecording())); connect(eventPlayer, SIGNAL(playClicked(int)), this, SLOT(eventPlayerPlayClicked(int))); connect(eventPlayer, SIGNAL(pauseClicked()), this, SLOT(eventPlayerPauseClicked())); connect(eventPlayer, SIGNAL(rewindToStartClicked()), this, SLOT(eventPlayerRewindToStartClicked())); connect(eventPlayer, SIGNAL(forwardToEndClicked()), this, SLOT(eventPlayerForwardToEndClicked())); connect(eventPlayer, SIGNAL(rewindClicked()), this, SLOT(eventPlayerRewindClicked())); connect(eventPlayer, SIGNAL(stopClicked()), this, SLOT(eventPlayerStopClicked())); connect(eventPlayer, SIGNAL(nextPackets(QVector<Packet>)), streamReader, SLOT(parsePackets(QVector<Packet>))); connect(ui->ltWidget, SIGNAL(driverSelected(int)), ui->driverDataWidget, SLOT(printDriverData(int))); connect(ui->ltWidget, SIGNAL(driverDoubleClicked(int)), this, SLOT(ltWidgetDriverSelected(int))); ui->messageBoardWidget->setVisible(false); QStringList args = qApp->arguments(); if (args.size() > 1) { if (eventPlayer->loadFromFile(args.at(1)) == false) { QMessageBox::critical(this, "Error opening file!", "Could not open specified file, or the file is corrupted."); connectToServer(); return; } setWindowTitle("FILT - " + args.at(1)); ui->actionRecord->setVisible(false); ui->actionStop_recording->setVisible(false); eventPlayerAction->setVisible(true); delayWidgetAction->setVisible(false); playing = true; eventPlayer->startPlaying(); } else { if (settings->value("ui/auto_connect").toBool()) connectToServer(); else { ui->messageBoardWidget->showStartupBoard(); showSessionBoard(true); } } } LTWindow::~LTWindow() { if (recording) eventRecorder->stopRecording(); saveSettings(); delete ui; } //------------------------- updating the data ---------------------- void LTWindow::eventDataChanged(const DataUpdates &dataUpdates) { if (!playing) setWindowTitle("F1LT - " + eventData.getEventInfo().eventName); if (!playing && !recording && !ui->actionRecord->isEnabled()) ui->actionRecord->setEnabled(true); if (dataUpdates.commentaryUpdate) { ui->commentaryWidget->update(); } // if (eventData.getCommentary().size() == 0 && ui->commentaryWidget->getCommentary().size() > 0) // ui->commentaryWidget->clear(); // ui->trackStatusWidget->updateTrackStatus(eventData); ui->eventStatusWidget->updateEventStatus(); ui->sessionDataWidget->updateData(dataUpdates); if ((ui->tabWidget->currentIndex() == 2) && dataUpdates.weatherUpdate) ui->weatherChartsWidget->updateCharts(); // if (recording) // eventRecorder->updateEventData(eventData); ui->ltWidget->updateLT(); if (trackRecordsDialog->isVisible()) trackRecordsDialog->update(); } void LTWindow::driverDataChanged(int carID, const DataUpdates &) { if (!playing && !recording && !ui->actionRecord->isEnabled()) ui->actionRecord->setEnabled(true); if (carID > -1) { ui->ltWidget->updateLT(); ui->sessionDataWidget->updateFastestLaps(); if (ui->tabWidget->currentIndex() == 0) { ui->driverDataWidget->updateDriverData(carID); } for (int i = 0; i < ltcDialog.size(); ++i) ltcDialog[i]->driverUpdated(*eventData.getDriverDataByIdPtr(carID)); for (int i = 0; i < h2hDialog.size(); ++i) h2hDialog[i]->driverUpdated(*eventData.getDriverDataByIdPtr(carID)); for (int i = 0; i < fadDialog.size(); ++i) fadDialog[i]->driverUpdated(*eventData.getDriverDataByIdPtr(carID)); if (saw->isVisible()) saw->update(); if (stw->isVisible()) stw->update(); if (trackRecordsDialog->isVisible()) trackRecordsDialog->update(); } } void LTWindow::dataChanged(const DataUpdates &dataUpdates) { if (playing) setWindowTitle("F1LT - " + eventData.getEventInfo().eventName + " (" + eventPlayer->playedFile() + ")"); if (dataUpdates.commentaryUpdate) { ui->commentaryWidget->update(); } // ui->trackStatusWidget->updateTrackStatus(eventData); ui->eventStatusWidget->updateEventStatus(); if (!eventPlayer->isPlaying()) ui->sessionDataWidget->updateEventInfo(); // ui->sessionDataWidget->updateFastestLaps(); // ui->sessionDataWidget->updateSpeedRecords(); // ui->sessionDataWidget->updatePitStops(true); ui->sessionDataWidget->updateData(dataUpdates); // if (currDriver >= 0) ui->driverDataWidget->updateDriverData(dataUpdates);//printDriverData(currDriver); for (int i = 0; i < ltcDialog.size(); ++i) { ltcDialog[i]->updateData(dataUpdates); } for (int i = 0; i < h2hDialog.size(); ++i) { h2hDialog[i]->updateData(dataUpdates); } for (int i = 0; i < fadDialog.size(); ++i) { fadDialog[i]->updateData(dataUpdates); } ui->ltWidget->updateLT(); if ((ui->tabWidget->currentIndex() == 2) && dataUpdates.weatherUpdate) ui->weatherChartsWidget->updateCharts(); if (saw->isVisible()) saw->update(); if (stw->isVisible()) stw->update(); if (trackRecordsDialog->isVisible()) trackRecordsDialog->update(); } void LTWindow::on_tabWidget_currentChanged(int index) { switch(index) { case 0: ui->driverDataWidget->updateView(); if (currDriver >= 0) ui->driverDataWidget->updateDriverData(currDriver); break; case 1: ui->sessionDataWidget->updateData(DataUpdates(true)); break; } } void LTWindow::on_actionLap_time_comparison_triggered() { for (int i = 0; i < ltcDialog.size(); ++i) { if (!ltcDialog[i]->isVisible()) { ltcDialog[i]->show(ui->ltWidget->getCurrentDriverId()); return; } } if (ltcDialog.size() < 30) { LapTimeComparisonDialog *ltc = new LapTimeComparisonDialog(); ltc->show(ui->ltWidget->getCurrentDriverId()); ltc->setFont(prefs->getMainFont()); ltcDialog.append(ltc); } } void LTWindow::on_actionHead_to_head_triggered() { for (int i = 0; i < h2hDialog.size(); ++i) { if (!h2hDialog[i]->isVisible()) { h2hDialog[i]->show(ui->ltWidget->getCurrentDriverId()); return; } } if (h2hDialog.size() < 30) { HeadToHeadDialog *h2h = new HeadToHeadDialog(); h2h->show(ui->ltWidget->getCurrentDriverId()); h2h->setFont(prefs->getMainFont()); h2hDialog.append(h2h); } } void LTWindow::on_actionFollow_a_driver_triggered() { for (int i = 0; i < fadDialog.size(); ++i) { if (!fadDialog[i]->isVisible()) { fadDialog[i]->show(ui->ltWidget->getCurrentDriverId()); return; } } if (fadDialog.size() < eventData.getDriversData().size()) { FollowADriverDialog *fad = new FollowADriverDialog(); fad->show(ui->ltWidget->getCurrentDriverId()); fad->setFont(prefs->getMainFont()); fadDialog.append(fad); } } void LTWindow::sessionStarted() { if (!sessionTimer->isActive() && ((!playing && !eventData.isQualiBreak()) || (playing && eventPlayer->isPlaying() && !eventPlayer->isPaused()))) { sessionTimer->start(1000); driverTrackerWidget->startTimer(1000); if (eventData.isSessionStarted() && !playing) { delayWidget->setEnabled(true); if (!recording && settings->value("ui/auto_record").toBool() && !eventRecorder->isSessionRecorded()) startRecording(true); } } } void LTWindow::showNoSessionBoard(bool show, QString msg) { if (show) { //ui->tableWidget->clear(); ui->ltWidget->clearData(); ui->commentaryWidget->clear(); ui->driverDataWidget->clearData(); ui->sessionDataWidget->clearData(); driverTrackerWidget->setup(); ui->messageBoardWidget->showSessionBoard(msg); showSessionBoard(true); } else { //here the new session is started showSessionBoard(false); eventRecorder->setSessionRecorded(false); ui->ltWidget->updateLT(); } } void LTWindow::updateWeather() { if (ui->tabWidget->currentIndex() == 2) ui->weatherChartsWidget->updateCharts(); } void LTWindow::onNewVersionAvailable() { updatesCheckerDialog->show(false); } void LTWindow::ltWidgetDriverSelected(int id) { ui->driverDataWidget->printDriverData(id); ui->tabWidget->setCurrentIndex(0); } void LTWindow::timeout() { if (recording) eventRecorder->timeout(); if (eventPlayer->isPlaying()) eventPlayer->timeout(); ui->eventStatusWidget->updateEventStatus(); // if (driverTrackerWidget->isVisible()) // driverTrackerWidget->update(); //during quali timer is stopped when we have red flag if (eventData.isSessionStarted()) { if (!playing && !recording && settings->value("ui/auto_record").toBool() && !eventRecorder->isSessionRecorded()) startRecording(true); } if (!recording && !playing && !eventData.isSessionStarted()) { sessionTimer->stop(); driverTrackerWidget->stopTimer(); } } //-------------------- settings ---------------------------- void LTWindow::loadSettings() { NetworkSettings::getInstance().loadSettings(*settings); QFont mainFont, commentaryFont; QString sbuf = settings->value("fonts/main_family").toString(); mainFont.setFamily(sbuf); int ibuf = settings->value("fonts/main_size").toInt(); mainFont.setPointSize(ibuf); ibuf = settings->value("fonts/main_weight").toInt(); mainFont.setWeight(ibuf); bool bbuf = settings->value("fonts/main_italic").toBool(); mainFont.setItalic(bbuf); // prefs->setMainFont(mainFont); sbuf = settings->value("fonts/commentary_family").toString(); commentaryFont.setFamily(sbuf); ibuf = settings->value("fonts/commentary_size").toInt(); commentaryFont.setPointSize(ibuf); ibuf = settings->value("fonts/commentary_weight").toInt(); commentaryFont.setWeight(ibuf); bbuf = settings->value("fonts/commentary_italic").toBool(); commentaryFont.setItalic(bbuf); // prefs->setCommentaryFont(commentaryFont); // prefs->setSplitterOpaqueResize(settings->value("ui/ltresize").toBool()); // prefs->setAlternatingRowColors(settings->value("ui/alt_colors").toBool()); // prefs->setAutoRecord(settings->value("ui/auto_record").toBool()); ui->splitter->setOpaqueResize(settings->value("ui/ltresize").toBool()); //ui->tableWidget->setAlternatingRowColors(settings->value("ui/alt_colors").toBool()); setFonts(mainFont, commentaryFont); restoreGeometry(settings->value("ui/window_geometry").toByteArray()); ui->splitter->restoreState(settings->value("ui/splitter_pos").toByteArray()); ui->tabWidget->setCurrentIndex(settings->value("ui/current_tab1").toInt()); if (ui->tabWidget->currentIndex() == 0) ui->driverDataWidget->setCurrentIndex(settings->value("ui/current_tab2").toInt()); else if (ui->tabWidget->currentIndex() == 1) ui->sessionDataWidget->setCurrentIndex(settings->value("ui/current_tab2").toInt()); // prefs->setReverseOrderLapHistory(settings->value("ui/reversed_lap_history").toBool()); // prefs->setReverseOrderHeadToHead(settings->value("ui/reversed_head_to_head").toBool()); // prefs->setReverseOrderLapTimeComparison(settings->value("ui/reversed_lap_time_comparison").toBool()); ui->ltWidget->setDrawCarThumbnails(settings->value("ui/car_thumbnails").toBool()); eventRecorder->setAutoSaveRecord(settings->value("ui/auto_save_record", -1).toInt()); eventRecorder->setAutoStopRecord(settings->value("ui/auto_stop_record", -1).toInt()); stw->loadSettings(*settings); driverTrackerWidget->loadSettings(settings); ltFilesManagerDialog->loadSettings(settings); trackRecordsDialog->loadSettings(*settings); ui->commentaryWidget->loadSettings(*settings); QList<QColor> colors = ColorsManager::getInstance().getColors(); for (int i = 0; i < ColorsManager::getInstance().getColors().size(); ++i) { QVariant color = settings->value(QString("ui/color_%1").arg(i), colors[i]); colors[i] = color.value<QColor>(); } ColorsManager::getInstance().setColors(colors); colors = ColorsManager::getInstance().getDriverColors(); for (int i = 0; i < ColorsManager::getInstance().getDriverColors().size(); ++i) { QVariant color = settings->value(QString("ui/driver_color_%1").arg(i), colors[i]); colors[i] = color.value<QColor>(); } ColorsManager::getInstance().setDriverColors(colors); saw->loadSettings(*settings); updatesCheckerDialog->loadSettings(*settings); if (settings->value("ui/check_for_updates", true).toBool()) updatesCheckerDialog->checkForUpdates(); } void LTWindow::saveSettings() { // QString passwd = encodePasswd(settings->value("login/passwd").toString()); // encodePasswd(passwd); NetworkSettings::getInstance().saveSettings(*settings); settings->setValue("ui/window_geometry", saveGeometry()); settings->setValue("ui/splitter_pos", ui->splitter->saveState()); settings->setValue("ui/current_tab1", ui->tabWidget->currentIndex()); if (ui->tabWidget->currentIndex() == 0) settings->setValue("ui/current_tab2", ui->driverDataWidget->currentIndex()); else if (ui->tabWidget->currentIndex() == 1) settings->setValue("ui/current_tab2", ui->sessionDataWidget->currentIndex()); saw->saveSettings(*settings); stw->saveSettings(*settings); driverTrackerWidget->saveSettings(settings); ltFilesManagerDialog->saveSettings(settings); trackRecordsDialog->saveSettings(*settings); ui->commentaryWidget->saveSettings(*settings); for (int i = 0; i < ColorsManager::getInstance().getColors().size(); ++i) { QVariant color = ColorsManager::getInstance().getColors()[i]; settings->setValue(QString("ui/color_%1").arg(i), color); } for (int i = 0; i < ColorsManager::getInstance().getDriverColors().size(); ++i) { QVariant color = ColorsManager::getInstance().getDriverColors()[i]; settings->setValue(QString("ui/driver_color_%1").arg(i), color); } updatesCheckerDialog->saveSettings(*settings); // settings->setValue("ui/ltresize", prefs->isSplitterOpaqueResize()); // settings->setValue("ui/alt_colors", prefs->isAlternatingRowColors()); // settings->setValue("ui/reversed_lap_history", prefs->isReverseOrderLapHistory()); // settings->setValue("ui/reversed_head_to_head", prefs->isReverseOrderHeadToHead()); // settings->setValue("ui/reversed_lap_time_comparison", prefs->isReverseOrderLapTimeComparison()); // settings->setValue("ui/auto_record", prefs->isAutoRecord()); } void LTWindow::on_actionPreferences_triggered() { if (prefs->exec(settings) == QDialog::Accepted) { setFonts(prefs->getMainFont(), prefs->getCommentaryFont()); ui->splitter->setOpaqueResize(prefs->isSplitterOpaqueResize()); //ui->tableWidget->setAlternatingRowColors(prefs->isAlternatingRowColors()); eventRecorder->setAutoStopRecord(settings->value("ui/auto_stop_record").toInt()); eventRecorder->setAutoSaveRecord(settings->value("ui/auto_save_record").toInt()); NetworkSettings::getInstance().setProxy(prefs->getProxy(), prefs->proxyEnabled()); for (int i = 0; i < h2hDialog.size(); ++i) { if (h2hDialog[i]->isVisible()) h2hDialog[i]->updateData(); } for (int i = 0; i < ltcDialog.size(); ++i) { if (ltcDialog[i]->isVisible()) ltcDialog[i]->updateData(); } ui->driverDataWidget->updateDriverData(currDriver); ui->ltWidget->setDrawCarThumbnails(settings->value("ui/car_thumbnails").toBool()); driverTrackerWidget->drawTrackerClassification(settings->value("ui/draw_tracker_classification").toBool()); } } void LTWindow::setFonts(const QFont &mainFont, const QFont &commentaryFont) { ui->ltWidget->setFont(mainFont); ui->driverDataWidget->setFont(mainFont, commentaryFont); ui->sessionDataWidget->setFont(mainFont); for (int i = 0; i < h2hDialog.size(); ++i) h2hDialog[i]->setFont(mainFont); for (int i = 0; i < ltcDialog.size(); ++i) ltcDialog[i]->setFont(mainFont); for (int i = 0; i < fadDialog.size(); ++i) fadDialog[i]->setFont(mainFont); ui->commentaryWidget->setFont(commentaryFont); // ui->trackStatusWidget->setFont(mainFont); ui->eventStatusWidget->setFont(mainFont); prefs->setFonts(mainFont, commentaryFont); trackRecordsDialog->setFont(mainFont); stw->setFont(mainFont); } bool LTWindow::close() { for (int i = 0; i < h2hDialog.size(); ++i) h2hDialog[i]->close(); for (int i = 0; i < ltcDialog.size(); ++i) ltcDialog[i]->close(); for (int i = 0; i < fadDialog.size(); ++i) fadDialog[i]->close(); if (saw->isVisible()) saw->close(); if (stw->isVisible()) stw->close(); if (driverTrackerWidget->isVisible()) driverTrackerWidget->close(); if (trackRecordsDialog->isVisible()) trackRecordsDialog->close(); TrackRecords::getInstance().saveTrackRecords(F1LTCore::trackRercordsFile(false)); return QMainWindow::close(); } void LTWindow::setupDialogs() { for (int i = 0; i < h2hDialog.size(); ++i) h2hDialog[i]->loadDriversList(); for (int i = 0; i < ltcDialog.size(); ++i) ltcDialog[i]->loadDriversList(); for (int i = 0; i < fadDialog.size(); ++i) fadDialog[i]->loadDriversList(); if (stw->isVisible()) stw->loadDriversList(); driverTrackerWidget->setup(); ui->sessionDataWidget->resizeTrackMap(); } //-------------------- connection with server ---------------------- void LTWindow::tryAuthorize() { connectionProgress->setWindowModality(Qt::WindowModal); connectionProgress->setLabelText("Connecting..."); connectionProgress->setCancelButton(0); connectionProgress->setRange(0,0); connectionProgress->setMinimumDuration(0); connectionProgress->show(); } void LTWindow::authorized(QString) { connectionProgress->cancel(); } void LTWindow::authorizationError() { if (!playing) { if (connectionProgress->isVisible()) connectionProgress->cancel(); QMessageBox::critical(this, tr("Login error!"), tr("Could not login to the server!\nCheck your email and password")); on_actionConnect_triggered(); ui->actionRecord->setEnabled(false); } } void LTWindow::on_actionConnect_triggered() { if (loginDialog->exec(NetworkSettings::getInstance().getUser(), NetworkSettings::getInstance().getPassword(), NetworkSettings::getInstance().getProxy(), NetworkSettings::getInstance().usingProxy()) == QDialog::Accepted) { if (playing) { eventPlayer->stopPlaying(); eventPlayerStopClicked(false); } streamReader->disconnectFromLTServer(); QString email = loginDialog->getEmail(); QString passwd = loginDialog->getPasswd(); NetworkSettings::getInstance().setUserPassword(email, passwd); NetworkSettings::getInstance().setProxy(loginDialog->getProxy(), loginDialog->proxyEnabled()); SeasonData::getInstance().checkSeasonData(); streamReader->connectToLTServer(); // settings->setValue("login/email", email); // QString encPasswd = encodePasswd(passwd); // settings->setValue("login/passwd", encPasswd); showSessionBoard(false); setupDialogs(); } } void LTWindow::connectToServer() { QString email = NetworkSettings::getInstance().getUser(); QString passwd = NetworkSettings::getInstance().getPassword(); if (email == "" || passwd == "") { if (loginDialog->exec() == QDialog::Accepted) { email = loginDialog->getEmail(); passwd = loginDialog->getPasswd(); NetworkSettings::getInstance().setUserPassword(email, passwd); NetworkSettings::getInstance().setProxy(loginDialog->getProxy(), loginDialog->proxyEnabled()); SeasonData::getInstance().checkSeasonData(); streamReader->connectToLTServer(); driverTrackerWidget->setup(); // settings->setValue("login/email", email); // passwd = encodePasswd(loginDialog->getPasswd()); // settings->setValue("login/passwd", passwd); } } else { streamReader->connectToLTServer(); driverTrackerWidget->setup(); } } void LTWindow::error(QAbstractSocket::SocketError er) { if (!playing) { ui->actionRecord->setEnabled(false); if (QMessageBox::critical(this, tr("Connection error!"), tr("There was an error with connection to LT server\n Error code: ") + QString("%1").arg(er), QMessageBox::Retry, QMessageBox::Close) == QMessageBox::Retry) { //try to connect again streamReader->disconnectFromLTServer(); connectToServer(); } // else // { // ui->messageBoardWidget->showStartupBoard(); // showSessionBoard(true); // } } } void LTWindow::error(QNetworkReply::NetworkError er) { if (!playing) { ui->actionRecord->setEnabled(false); if (QMessageBox::critical(this, tr("Connection error!"), tr("There was an error with connection to LT server\n Error code: ") + QString("%1").arg(er), QMessageBox::Retry, QMessageBox::Close) == QMessageBox::Retry) { //try to connect again streamReader->disconnectFromLTServer(); connectToServer(); } // else // { // ui->messageBoardWidget->showStartupBoard(); // showSessionBoard(true); // } } } //-------------------- about ------------------------ void LTWindow::on_actionAbout_triggered() { aboutDialog->exec(); //QMessageBox::about(this, "About F1LT", "<b>F1LT</b> v" + F1LTCore::programVersion()+"<br/>by Mariusz Pilarek, 2012<br/><a href=\"http://f1lt.pl/\">Home site</a>"); } void LTWindow::on_actionAbout_Qt_triggered() { QMessageBox::aboutQt(this); } //-------------------- event recorder ---------------------------- void LTWindow::startRecording(bool autoRecord) { //if the current session is recorded while auto record has turned on we don't do anything if (autoRecord == true && eventRecorder->isSessionRecorded() == true) return; recording = true; ui->actionStop_recording->setEnabled(true); ui->actionRecord->setEnabled(false); ui->actionLT_files_data_base->setEnabled(false); // ui->actionRecord->setIcon(QIcon(":/ui_icons/stop.png")); ui->actionOpen->setEnabled(false); eventRecorder->startRecording(delayWidget->getDelay()); // connect(streamReader, SIGNAL(packetParsed(Packet)), eventRecorder, SLOT(appendPacket(Packet))); connect(streamReader, SIGNAL(packetParsed(QPair<Packet, qint64>)), eventRecorder, SLOT(appendPacket(QPair<Packet, qint64>))); if (!sessionTimer->isActive()) { sessionTimer->start(); driverTrackerWidget->startTimer(); } } void LTWindow::stopRecording(bool autoStop) { recording = false; ui->actionOpen->setEnabled(true); ui->actionRecord->setEnabled(true); ui->actionLT_files_data_base->setEnabled(true); ui->actionStop_recording->setEnabled(false); if (!autoStop) eventRecorder->stopRecording(); // disconnect(streamReader, SIGNAL(packetParsed(Packet)), eventRecorder, SLOT(appendPacket(Packet))); disconnect(streamReader, SIGNAL(packetParsed(QPair<Packet, qint64>)), eventRecorder, SLOT(appendPacket(QPair<Packet, qint64>))); } void LTWindow::on_actionRecord_triggered() { startRecording(false); } void LTWindow::on_actionStop_recording_triggered() { stopRecording(false); } void LTWindow::autoStopRecording() { stopRecording(true); } //-------------------- event player ---------------------------- void LTWindow::on_actionOpen_triggered() { if (playing) eventPlayer->pausePlaying(); QString ltDir = settings->value("ui/ltdir").toString(); if (ltDir == "") ltDir = F1LTCore::ltDataHomeDir(); QString fName = QFileDialog::getOpenFileName(this, "Select archive LT event file", ltDir, "*.lt"); if (!fName.isNull()) { sessionTimer->stop(); driverTrackerWidget->stopTimer(); QFileInfo fi(fName); ltDir = fi.absolutePath(); settings->setValue("ui/ltdir", ltDir); if (recording) stopRecording(false); eventPlayerOpenFile(fName); } } void LTWindow::on_actionLT_files_data_base_triggered() { if (playing) eventPlayer->pausePlaying(); QString fName = ltFilesManagerDialog->exec(); if (!fName.isNull()) { sessionTimer->stop(); driverTrackerWidget->stopTimer(); if (recording) stopRecording(false); eventPlayerOpenFile(fName); } } void LTWindow::eventPlayerOpenFile(QString fName) { if (eventPlayer->loadFromFile(fName) == false) { QMessageBox::critical(this, "Error opening file!", "Could not open specified file, or the file is corrupted."); return; } QFileInfo fInfo(fName); QString name = fInfo.fileName(); showSessionBoard(false); //ui->tableWidget->clear(); ui->commentaryWidget->clear(); ui->driverDataWidget->clearData(); ui->sessionDataWidget->clearData(); ui->ltWidget->loadCarImages(); // eventData.clear(); ui->actionRecord->setVisible(false); ui->actionStop_recording->setVisible(false); eventPlayerAction->setVisible(true); delayWidgetAction->setVisible(false); streamReader->disconnectFromLTServer(); // streamReader->clearData(); playing = true; eventPlayer->startPlaying(); ui->eventStatusWidget->updateEventStatus(); setupDialogs(); saw->resetView(); } void LTWindow::eventPlayerPlayClicked(int interval) { sessionTimer->start(interval); driverTrackerWidget->startTimer(interval); } void LTWindow::eventPlayerPauseClicked() { sessionTimer->stop(); driverTrackerWidget->stopTimer(); } void LTWindow::eventPlayerRewindToStartClicked() { sessionTimer->stop(); driverTrackerWidget->stopTimer(); eventData.reset(); ui->sessionDataWidget->clearData(); eventPlayer->startPlaying(); driverTrackerWidget->setup(); } void LTWindow::eventPlayerForwardToEndClicked() { sessionTimer->stop(); driverTrackerWidget->stopTimer(); } void LTWindow::eventPlayerRewindClicked() { //clear all data ui->sessionDataWidget->clearFastestLaps(); ui->ltWidget->clearModelsData(); eventData.reset(); //it should be safe here - drivers vector will remain the same in eventdata // driverTrackerWidget->setup(); } void LTWindow::eventPlayerStopClicked(bool connect) { streamReader->clearData(); eventPlayerAction->setVisible(false); delayWidgetAction->setVisible(true); ui->actionRecord->setVisible(true); ui->actionStop_recording->setVisible(true); //ui->tableWidget->clear(); ui->ltWidget->clearData(); ui->driverDataWidget->clearData(); ui->sessionDataWidget->clearData(); ui->commentaryWidget->clear(); saw->resetView(); eventRecorder->setSessionRecorded(false); sessionTimer->stop(); driverTrackerWidget->stopTimer(); playing = false; SeasonData::getInstance().loadSeasonFile(); ui->ltWidget->loadCarImages(); setupDialogs(); setWindowTitle("F1LT"); if (connect) { if (settings->value("ui/auto_connect").toBool()) connectToServer(); else { ui->messageBoardWidget->showStartupBoard(); showSessionBoard(true); } } } void LTWindow::showSessionBoard(bool show) { if (show) { ui->splitter->setVisible(!show); ui->eventStatusWidget->setVisible(!show); ui->messageBoardWidget->setVisible(show); delayWidget->setEnabled(false); } else { ui->messageBoardWidget->setVisible(show); ui->eventStatusWidget->setVisible(!show); ui->splitter->setVisible(!show); // delayWidget->setEnabled(true); } ui->actionRecord->setEnabled(!show); ui->actionHead_to_head->setEnabled(!show); ui->actionLap_time_comparison->setEnabled(!show); ui->actionFollow_a_driver->setEnabled(!show); ui->actionSession_analysis->setEnabled(!show); ui->actionSession_times->setEnabled(!show); ui->actionDriver_tracker->setEnabled(!show); // ui->actionTrack_records->setEnabled(!show); } void LTWindow::on_actionSession_analysis_triggered() { saw->exec(); } void LTWindow::on_actionSession_times_triggered() { stw->exec(); } void LTWindow::on_actionDriver_tracker_triggered() { driverTrackerWidget->exec(); } void LTWindow::on_actionTrack_records_triggered() { trackRecordsDialog->exec(); } void LTWindow::on_actionCheck_for_updates_triggered() { updatesCheckerDialog->show(); }
zywhlc-f1lt
src/main_gui/ltwindow.cpp
C++
gpl3
35,484
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef ABOUTDIALOG_H #define ABOUTDIALOG_H #include <QDialog> namespace Ui { class AboutDialog; } class AboutDialog : public QDialog { Q_OBJECT public: explicit AboutDialog(QWidget *parent = 0); ~AboutDialog(); void loadChangelog(); void loadLicense(); private: Ui::AboutDialog *ui; }; #endif // ABOUTDIALOG_H
zywhlc-f1lt
src/main_gui/aboutdialog.h
C++
gpl3
1,894
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LTITEMDELEGATE_H #define LTITEMDELEGATE_H #include <QItemDelegate> #include "../core/eventdata.h" class LTItemDelegate: public QItemDelegate { public: LTItemDelegate(QObject* parent = 0) : QItemDelegate(parent) { } void paint(QPainter* painter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const; }; class LTMainItemDelegate : public LTItemDelegate { public: LTMainItemDelegate(QObject* parent = 0, bool draw = true, int size = 75) : LTItemDelegate(parent), drawCars(draw), thumbnailsSize(size) { } void setDrawCarThumbnails(bool val) { drawCars = val; } void paint(QPainter* painter, const QStyleOptionViewItem& rOption, const QModelIndex& rIndex) const; private: bool drawCars; int thumbnailsSize; }; #endif // LTITEMDELEGATE_H
zywhlc-f1lt
src/main_gui/ltitemdelegate.h
C++
gpl3
2,370
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LTWIDGET_H #define LTWIDGET_H #include <QItemDelegate> #include <QKeyEvent> #include <QResizeEvent> #include <QWheelEvent> #include <QWidget> #include "../core/eventdata.h" #include "ltitemdelegate.h" #include "models/ltmodel.h" namespace Ui { class LTWidget; } class LTWidget : public QWidget { Q_OBJECT public: explicit LTWidget(QWidget *parent = 0); ~LTWidget(); void updateLT(); virtual void setFont(const QFont &font); // void updateRaceEvent(int ddIdx = -1); // void updateDriver(int driverIdx); // void updatePracticeEvent(int ddIdx = -1); // void updateQualiEvent(int ddIdx = -1); void loadCarImages(); void setDrawCarThumbnails(bool val) { drawCarThumbnails = val; itemDelegate->setDrawCarThumbnails(val); resizeEvent(0); updateLT(); } void clearData(); void clearModelsData() { if (ltModel != 0) ltModel->clearData(); } int getCurrentDriverId() { return currDriverId; } protected: virtual void resizeEvent(QResizeEvent *); signals: void driverSelected(int id); void driverDoubleClicked(int id); private slots: void on_tableView_clicked(const QModelIndex &index); void on_tableView_doubleClicked(const QModelIndex &index); void on_tableView_headerClicked(int column); private: Ui::LTWidget *ui; EventData &eventData; LTPackets::EventType eventType; int currDriverId; bool drawCarThumbnails; int showDiff; //1 - time (best, q1), 2 - q2, 3 - q3, 4 - interval LTModel *ltModel; LTMainItemDelegate *itemDelegate; int thumbnailsSize; }; #endif // LTWIDGET_H
zywhlc-f1lt
src/main_gui/ltwidget.h
C++
gpl3
3,227
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef SESSIONDATAWIDGET_H #define SESSIONDATAWIDGET_H #include <QKeyEvent> #include <QList> #include <QPair> #include <QWidget> #include <QTableWidgetItem> #include "../core/colorsmanager.h" #include "../core/eventdata.h" #include "../net/packetparser.h" #include "models/fastestlapsmodel.h" #include "models/pitstopsmodel.h" #include "models/speedrecordsmodel.h" namespace Ui { class SessionDataWidget; } class SessionDataWidget : public QWidget { Q_OBJECT public: explicit SessionDataWidget(QWidget *parent = 0); ~SessionDataWidget(); int currentIndex(); void setCurrentIndex(int); void setFont(const QFont &); void setupContents(); void updateData(const DataUpdates &dataUpdates); void updateSpeedRecords(); void updateFastestLaps(); void updatePitStops(bool clear = false); void updateEventInfo(); void resizeTrackMap(); void clearData(); void clearFastestLaps(); protected: void resizeEvent(QResizeEvent *); void keyPressEvent(QKeyEvent *); private slots: void on_tabWidget_currentChanged(int index); private: QTableWidgetItem* setItem(QTableWidget *table, int row, int col, QString text = "", Qt::ItemFlags flags = Qt::NoItemFlags, int align = Qt::AlignCenter, QColor textColor = ColorsManager::getInstance().getColor(LTPackets::DEFAULT), QBrush background = QBrush()); Ui::SessionDataWidget *ui; EventData &eventData; SpeedRecordsModel speedRecordsModel; FastestLapsModel fastestLapsModel; PitStopsModel pitStopsModel; LTEvent currentEvent; }; #endif // SESSIONDATAWIDGET_H
zywhlc-f1lt
src/main_gui/sessiondatawidget.h
C++
gpl3
3,173
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "lttableview.h" #include "models/ltmodel.h" #include <QKeyEvent> LTTableView::LTTableView(QWidget *parent) : QTableView(parent) { } void LTTableView::updateColumn(QModelIndex index) { LTModel *ltModel = static_cast<LTModel*>(model()); for (int i = ltModel->firstRow(); i <= ltModel->lastRow(); ++i) { QModelIndex idx = ltModel->index(i, index.column()); update(idx); } } void LTTableView::keyPressEvent(QKeyEvent *event) { QModelIndex index = currentIndex(); LTModel *ltModel = static_cast<LTModel*>(model()); if (event->key() == Qt::Key_Up && index.row() > ltModel->firstRow()) { QModelIndex newIndex = ltModel->index(index.row()-1, 0); setCurrentIndex(newIndex); emit clicked(newIndex); } if (event->key() == Qt::Key_Down && index.row() < ltModel->lastRow()) { QModelIndex newIndex = ltModel->index(index.row()+1, 0); setCurrentIndex(newIndex); emit clicked(newIndex); } if (event->key() == Qt::Key_Return) { QTableView::keyPressEvent(event); emit doubleClicked(index); } if (event->key() == Qt::Key_Home) { QModelIndex newIndex = ltModel->index(ltModel->firstRow(), 0); setCurrentIndex(newIndex); emit clicked(newIndex); } if (event->key() == Qt::Key_End) { QModelIndex newIndex = ltModel->index(ltModel->lastRow(), 0); setCurrentIndex(newIndex); emit clicked(newIndex); } if (event->key() == Qt::Key_PageDown) { int row = index.row() + ltModel->driverRows()/2; if (row > ltModel->lastRow()) row = ltModel->lastRow(); QModelIndex newIndex = ltModel->index(row, 0); setCurrentIndex(newIndex); emit clicked(newIndex); } if (event->key() == Qt::Key_PageUp) { int row = index.row() - ltModel->driverRows()/2; if (row < ltModel->firstRow()) row = ltModel->firstRow(); QModelIndex newIndex = ltModel->index(row, 0); setCurrentIndex(newIndex); emit clicked(newIndex); } } void LTTableView::resizeEvent(QResizeEvent *) { } void LTTableView::wheelEvent(QWheelEvent *event) { QModelIndex index = currentIndex(); LTModel *ltModel = static_cast<LTModel*>(model()); if (event->delta() < 0 && index.row() < ltModel->lastRow()) { QModelIndex newIndex = ltModel->index(index.row()+1, 0); setCurrentIndex(newIndex); emit clicked(newIndex); } else if (event->delta() > 0 && index.row() > ltModel->firstRow()) { QModelIndex newIndex = ltModel->index(index.row()-1, 0); setCurrentIndex(newIndex); emit clicked(newIndex); } QTableView::wheelEvent(event); } void LTTableView::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { QModelIndex index = indexAt(event->pos()); LTModel *ltModel = static_cast<LTModel*>(model()); if (ltModel && ltModel->indexInDriverRowsData(index)) QTableView::mousePressEvent(event); if (index.row() == 0) emit headerClicked(index.column()); } }
zywhlc-f1lt
src/main_gui/lttableview.cpp
C++
gpl3
4,744
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef DELAYWIDGET_H #define DELAYWIDGET_H #include <QWidget> namespace Ui { class DelayWidget; } class DelayWidget : public QWidget { Q_OBJECT public: explicit DelayWidget(QWidget *parent = 0); ~DelayWidget(); int getDelay() const { return delay; } signals: void delayChanged(int previousDelay, int delay); public slots: void synchronizingTimer(bool); private slots: void on_spinBox_valueChanged(int arg1); private: Ui::DelayWidget *ui; int delay; }; #endif // DELAYWIDGET_H
zywhlc-f1lt
src/main_gui/delaywidget.h
C++
gpl3
2,091
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "ltwidget.h" #include "ui_ltwidget.h" #include <QDebug> #include <QPainter> #include "models/practicemodel.h" #include "models/qualimodel.h" #include "models/racemodel.h" LTWidget::LTWidget(QWidget *parent) : QWidget(parent), ui(new Ui::LTWidget), eventData(EventData::getInstance()), eventType((LTPackets::EventType)0), currDriverId(0), ltModel(0), thumbnailsSize(75) { ui->setupUi(this); loadCarImages(); itemDelegate = new LTMainItemDelegate(ui->tableView, drawCarThumbnails, thumbnailsSize); ui->tableView->setItemDelegate(itemDelegate); //connect(ui->tableView, SIGNAL(headerClicked(int)), this, SLOT(on_tableView_headerClicked(int))); } LTWidget::~LTWidget() { if (ltModel) delete ltModel; delete ui; } void LTWidget::clearData() { if (ltModel) { delete ltModel; ltModel = 0; } } void LTWidget::loadCarImages() { showDiff = 0; currDriverId = 0; ImagesFactory::getInstance().getCarThumbnailsFactory().loadCarThumbnails(thumbnailsSize); } void LTWidget::setFont(const QFont &font) { ui->tableView->setFont(font); QWidget::setFont(font); } void LTWidget::updateLT() { if (eventType != eventData.getEventType() || !ltModel) { clearData(); if (eventData.getEventType() == LTPackets::PRACTICE_EVENT) { ltModel = new PracticeModel(this); ui->tableView->setModel(ltModel); } else if (eventData.getEventType() == LTPackets::QUALI_EVENT) { ltModel = new QualiModel(this); ui->tableView->setModel(ltModel); } else if (eventData.getEventType() == LTPackets::RACE_EVENT) { ltModel = new RaceModel(this); ui->tableView->setModel(ltModel); } resizeEvent(0); eventType = eventData.getEventType(); } // else // ui->tableView->reset(); if (ltModel) { ltModel->updateLT(); if (currDriverId > 0) ui->tableView->setCurrentIndex(ltModel->indexOf(currDriverId)); } } void LTWidget::resizeEvent(QResizeEvent *e) { int w = ui->tableView->viewport()->width();/*-viewport()->width()*0.0115*/;//event->size().width()-event->size().width()*0.0115; switch(eventData.getEventType()) { case LTPackets::RACE_EVENT: if (drawCarThumbnails) { ui->tableView->setColumnWidth(0, 0.04 * w); ui->tableView->setColumnWidth(1, 0.06 * w); ui->tableView->setColumnWidth(2, 0.115 * w); ui->tableView->setColumnWidth(3, 0.18 * w); ui->tableView->setColumnWidth(4, 0.06 * w); ui->tableView->setColumnWidth(5, 0.1 * w); ui->tableView->setColumnWidth(6, 0.12 * w); ui->tableView->setColumnWidth(7, 0.09 * w); ui->tableView->setColumnWidth(8, 0.09 * w); ui->tableView->setColumnWidth(9, 0.09 * w); ui->tableView->setColumnWidth(10, 0.06 * w); } else { ui->tableView->setColumnWidth(0, 0.05 * w); ui->tableView->setColumnWidth(1, 0.07 * w); ui->tableView->setColumnWidth(2, 0); ui->tableView->setColumnWidth(3, 0.22 * w); ui->tableView->setColumnWidth(4, 0.1 * w); ui->tableView->setColumnWidth(5, 0.11 * w); ui->tableView->setColumnWidth(6, 0.11 * w); ui->tableView->setColumnWidth(7, 0.1 * w); ui->tableView->setColumnWidth(8, 0.1 * w); ui->tableView->setColumnWidth(9, 0.1 * w); ui->tableView->setColumnWidth(10, 0.04 * w); } break; case LTPackets::PRACTICE_EVENT: if (drawCarThumbnails) { ui->tableView->setColumnWidth(0, 0.04 * w); ui->tableView->setColumnWidth(1, 0.05 * w); ui->tableView->setColumnWidth(2, 0.12 * w); ui->tableView->setColumnWidth(3, 0.2 * w); ui->tableView->setColumnWidth(4, 0.14 * w); ui->tableView->setColumnWidth(5, 0.11 * w); ui->tableView->setColumnWidth(6, 0.09 * w); ui->tableView->setColumnWidth(7, 0.09 * w); ui->tableView->setColumnWidth(8, 0.09 * w); ui->tableView->setColumnWidth(9, 0.09 * w); } else { ui->tableView->setColumnWidth(0, 0.05 * w); ui->tableView->setColumnWidth(1, 0.07 * w); ui->tableView->setColumnWidth(2, 0); ui->tableView->setColumnWidth(3, 0.2 * w); ui->tableView->setColumnWidth(4, 0.14 * w); ui->tableView->setColumnWidth(5, 0.18 * w); ui->tableView->setColumnWidth(6, 0.09 * w); ui->tableView->setColumnWidth(7, 0.09 * w); ui->tableView->setColumnWidth(8, 0.09 * w); ui->tableView->setColumnWidth(9, 0.09 * w); } break; case LTPackets::QUALI_EVENT: if (drawCarThumbnails) { ui->tableView->setColumnWidth(0, 0.04 * w); ui->tableView->setColumnWidth(1, 0.044 * w); ui->tableView->setColumnWidth(2, 0.12 * w); ui->tableView->setColumnWidth(3, 0.18 * w); ui->tableView->setColumnWidth(4, 0.1 * w); ui->tableView->setColumnWidth(5, 0.1 * w); ui->tableView->setColumnWidth(6, 0.1 * w); ui->tableView->setColumnWidth(7, 0.09 * w); ui->tableView->setColumnWidth(8, 0.09 * w); ui->tableView->setColumnWidth(9, 0.09 * w); ui->tableView->setColumnWidth(10, 0.06 * w); } else { ui->tableView->setColumnWidth(0, 0.05 * w); ui->tableView->setColumnWidth(1, 0.05 * w); ui->tableView->setColumnWidth(2, 0); ui->tableView->setColumnWidth(3, 0.21 * w); ui->tableView->setColumnWidth(4, 0.11 * w); ui->tableView->setColumnWidth(5, 0.11 * w); ui->tableView->setColumnWidth(6, 0.11 * w); ui->tableView->setColumnWidth(7, 0.1 * w); ui->tableView->setColumnWidth(8, 0.1 * w); ui->tableView->setColumnWidth(9, 0.1 * w); ui->tableView->setColumnWidth(10, 0.06 * w); } break; } //tu sie sypie przy przejsciu do nast. sesji if (ltModel) { for (int i = 0; i < ltModel->rowCount(); ++i) ui->tableView->setRowHeight(i, 22); } QWidget::resizeEvent(e); } void LTWidget::on_tableView_clicked(const QModelIndex &index) { if (ltModel) { if (ltModel->indexInDriverRowsData(index)) { const DriverData *dd = ltModel->getDriverData(index); currDriverId = dd->getCarID(); ltModel->selectDriver(currDriverId, index.column()); ltModel->updateLT(); emit driverSelected(currDriverId); } // ui->tableView->setCurrentIndex(index); } } void LTWidget::on_tableView_doubleClicked(const QModelIndex &index) { if (ltModel && ltModel->indexInDriverRowsData(index)) { const DriverData *dd = ltModel->getDriverData(index); currDriverId = dd->getCarID(); emit driverDoubleClicked(currDriverId); } } void LTWidget::on_tableView_headerClicked(int column) { if (ltModel) { ltModel->headerClicked(column); if (currDriverId > 0) { QModelIndex index = ltModel->indexOf(currDriverId); ui->tableView->setCurrentIndex(index); } } }
zywhlc-f1lt
src/main_gui/ltwidget.cpp
C++
gpl3
9,474
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef NOSESSIONBOARDWIDGET_H #define NOSESSIONBOARDWIDGET_H #include <QMouseEvent> #include <QtGui/QWidget> #include "ui_nosessionboardwidget.h" class NoSessionBoardWidget : public QWidget { Q_OBJECT public: NoSessionBoardWidget(QWidget *parent = 0); ~NoSessionBoardWidget(); void showSessionBoard(QString msg); void showStartupBoard(); protected: void mousePressEvent(QMouseEvent *); signals: void connectClicked(); void playClicked(); void loadClicked(); private: Ui::NoSessionBoardWidgetClass ui; }; #endif // NOSESSIONBOARDWIDGET_H
zywhlc-f1lt
src/main_gui/nosessionboardwidget.h
C++
gpl3
2,129
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef UPDATECHECKERDIALOG_H #define UPDATECHECKERDIALOG_H #include <QAbstractButton> #include <QDialog> #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QSettings> namespace Ui { class UpdatesCheckerDialog; } class UpdatesCheckerDialog : public QDialog { Q_OBJECT public: explicit UpdatesCheckerDialog(QWidget *parent = 0); ~UpdatesCheckerDialog(); void checkForUpdates(); bool newVersionIsAvailable(QString version); void loadSettings(QSettings &settings); void saveSettings(QSettings &settings); public slots: void finished(); void error(QNetworkReply::NetworkError); void show(bool check = true); signals: void newVersionAvailable(); private slots: void on_buttonBox_clicked(QAbstractButton *); private: Ui::UpdatesCheckerDialog *ui; QNetworkAccessManager manager; QNetworkRequest req; QNetworkReply *reply; }; #endif // UPDATECHECKERDIALOG_H
zywhlc-f1lt
src/main_gui/updatescheckerdialog.h
C++
gpl3
2,521
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "packetparser.h" #include <QDebug> #include "packetbuffer.h" #include "../core/trackrecords.h" bool PacketDecrypter::checkDecryption(QString stream) { for (int i = 0; i < stream.size(); ++i) { unsigned char c = (unsigned char)(stream[i].toAscii()); if ((int)c != 10 && ((int)c < 32 || (int)c > 126)) return false; } return true; } //============================================================= PacketParser::PacketParser(QObject *parent) : QObject(parent), parsing(false), packetNo(0), eventData(EventData::getInstance()), noSession(false) { packetBuffer = new PacketBuffer(this, this); } void PacketParser::setDelay(int, int delay) { packetBuffer->setDelay(delay); } void PacketParser::parseStreamBlock(const QByteArray &data) { streamData = data; Packet packet; int pos = 0; parsing = true; while(parsePacket(streamData, packet, pos)) { if (packet.encrypted && !eventData.key) { packet.longData.clear(); continue; } //after every SYS_KEY_FRAME packet decryption have to be reset if(!packet.carID && (packet.type == LTPackets::SYS_KEY_FRAME || packet.type == LTPackets::SYS_EVENT_ID)) decrypter.resetDecryption(); if (packetBuffer->hasToBeBuffered()) { packetBuffer->addPacket(packet); } else parseBufferedPackets(qMakePair(packet, QDateTime::currentMSecsSinceEpoch())); // Packet copyPacket = packet; // parseCarPacket(packet); // else // parseSystemPacket(packet); // emit packetParsed(copyPacket); packet.longData.clear(); } parsing = false; } void PacketParser::parseKeyFrame(const QByteArray &data) { streamData = data; Packet packet; int pos = 0; parsing = true; while(parsePacket(streamData, packet, pos)) { if (packet.encrypted && !eventData.key) { packet.longData.clear(); continue; } dataUpdates.setAllFalse(); if(!packet.carID && (packet.type == LTPackets::SYS_KEY_FRAME || packet.type == LTPackets::SYS_EVENT_ID)) decrypter.resetDecryption(); if (packet.carID) parseCarPacket(packet, false); else parseSystemPacket(packet, false); emit packetParsed(packet); packet.longData.clear(); } parsing = false; emit dataChanged(dataUpdates); } bool PacketParser::parsePacket(const QByteArray &buf, Packet &packet, int &pos) { static QByteArray pbuf; static int pbuf_length = 0; if (pbuf_length < 2) { int data_length = std::min(buf.size()-pos, 2 - pbuf_length); pbuf.append(buf.mid(pos, data_length)); pbuf_length += data_length; pos += data_length; if (pbuf_length < 2) return 0; } if (pos == buf.size()) return false; packet.type = LTPackets::getPacketType(pbuf); packet.carID = LTPackets::getCarPacket(pbuf); bool decryptPacket = false; if (packet.carID) { switch(packet.type) { case LTPackets::CAR_POSITION_UPDATE: packet.length = LTPackets::getSpecialPacketLength(pbuf); packet.data = LTPackets::getSpecialPacketData(pbuf); break; case LTPackets::CAR_POSITION_HISTORY: packet.length = LTPackets::getLongPacketLength(pbuf); packet.data = LTPackets::getLongPacketData(pbuf); decryptPacket = true; break; default: packet.length = LTPackets::getShortPacketLength(pbuf); packet.data = LTPackets::getShortPacketData(pbuf); decryptPacket = true; break; } } else { switch(packet.type) { case LTPackets::SYS_EVENT_ID: case LTPackets::SYS_KEY_FRAME: packet.length = LTPackets::getShortPacketLength(pbuf); packet.data = LTPackets::getShortPacketData(pbuf); break; case LTPackets::SYS_TIMESTAMP: packet.length = 2; packet.data = 0; decryptPacket = true; break; case LTPackets::SYS_WEATHER: case LTPackets::SYS_TRACK_STATUS: packet.length = LTPackets::getShortPacketLength(pbuf); packet.data = LTPackets::getShortPacketData(pbuf); decryptPacket = true; break; case LTPackets::SYS_COMMENTARY: case LTPackets::SYS_NOTICE: case LTPackets::SYS_SPEED: packet.length = LTPackets::getLongPacketLength(pbuf); packet.data = LTPackets::getLongPacketData(pbuf); decryptPacket = true; break; case LTPackets::SYS_COPYRIGHT: packet.length = LTPackets::getLongPacketLength(pbuf); packet.data = LTPackets::getLongPacketData(pbuf); break; case LTPackets::SYS_VALID_MARKER: case LTPackets::SYS_REFRESH_RATE: packet.length = 0;//LTPackets::getShortPacketLength(pbuf); packet.data = 0;//LTPackets::getShortPacketData(pbuf); break; default: packet.length = 0; packet.data = 0; break; } } // decryptPacket = false; packet.encrypted = decryptPacket; if (packet.length > 0) { int data_length = std::min(buf.size() - pos, (packet.length+2) - pbuf_length); pbuf.append(buf.mid(pos, data_length)); pbuf_length += data_length; pos += data_length; if (pbuf_length < (packet.length + 2)) return false; } if (packet.length > 0) { packet.longData.append(pbuf.mid(2, packet.length)); if (decryptPacket) { if (!decrypter.key) encryptedPackets.push_back(packet); else decrypter.decrypt(packet.longData); } } pbuf_length = 0; pbuf.clear(); return true; } void PacketParser::parseCarPacket(Packet &packet, bool emitSignal) { if (noSession) { eventData.frame = 0; noSession = false; emit noLiveSession(false, ""); } // dataUpdates.driverIds.insert(packet.carID); // qDebug()<<"CAR="<<packet.carID<<" "<<packet.type<<" "<<packet.data<<" "<<packet.length<<" "<<packet.longData.size()<<" "<<packet.longData.constData(); if (packet.carID > eventData.driversData.size() || packet.carID < 1) { // for (int i = 0; i < packet.longData.size(); ++i) // std::cout<<(int)packet.longData[i]<<" "; // std::cout<<std::endl; return; } Packet copyPacket = packet; if (packet.type != LTPackets::CAR_POSITION_HISTORY && !decrypter.checkDecryption(packet.longData)) { packet.longData = ""; packet.length = 0; // eventData.frame = 0; } //return; QString s; // DriverData dd; int ibuf; bool ok; PitData pd; switch(packet.type) { case LTPackets::CAR_POSITION_UPDATE: // dd.carID = packet.carID; // dd.pos = packet.data; // dd.numPits = 0; // dd.colorData.positionColor() = LTPackets::RED; // dd.colorData = ColorData(); if ((packet.carID-1) < eventData.driversData.size() && (packet.carID-1) >= 0 && eventData.driversData[packet.carID - 1].lapData.isEmpty()) { eventData.driversData[packet.carID - 1].carID = packet.carID; eventData.driversData[packet.carID - 1].lastLap.carID = packet.carID; eventData.driversData[packet.carID - 1].pos = packet.data; eventData.driversData[packet.carID - 1].colorData.positionColor() = LTPackets::RED; } break; case LTPackets::RACE_POSITION: //case LTPackets::PRACTICE_POSITION: //case LTPackets::QUALI_POSITION: ibuf = packet.longData.toInt(&ok); if (ok && ibuf > 0) { eventData.driversData[packet.carID-1].pos = eventData.driversData[packet.carID-1].lastLap.pos = ibuf; eventData.driversData[packet.carID-1].retired = false; if ((eventData.eventType == LTPackets::PRACTICE_EVENT || eventData.eventType == LTPackets::QUALI_EVENT) && !eventData.driversData[packet.carID-1].lapData.isEmpty()) { eventData.driversData[packet.carID-1].lapData.last().pos = ibuf; if (!eventData.driversData[packet.carID-1].posHistory.isEmpty()) eventData.driversData[packet.carID-1].posHistory.last() = ibuf; } } // else if ((eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString() == "STOP" || eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString() == "STOP" || eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString() == "STOP" || eventData.driversData[packet.carID-1].lastLap.lapTime.toString() == "RETIRED") && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; //If the packet data isn't a number, probably the decryption has failed. Set the frame number to 0 and wait for another SYS=2 packet to obtain the keyframe again // if (!ok) // eventData.frame = 0; eventData.driversData[packet.carID-1].colorData.positionColor() = (LTPackets::Colors)packet.data; break; case LTPackets::RACE_NUMBER: //case LTPackets::PRACTICE_NUMBER: //case LTPackets::QUALI_NUMBER: ibuf = packet.longData.toInt(&ok); if (ok && ibuf > 0) eventData.driversData[packet.carID-1].number = ibuf; eventData.driversData[packet.carID-1].colorData.numberColor() = (LTPackets::Colors)packet.data; eventData.driversData[packet.carID-1].updatePitStatus((LTPackets::Colors)packet.data, eventData); break; case LTPackets::RACE_DRIVER: //case LTPackets::PRACTICE_DRIVER: //case LTPackets::QUALI_DRIVER: if (packet.longData != "" /*&& packet.length > 0*/ && QString(packet.longData).indexOf(QRegExp("[A-Z]")) != -1)//eventData.driversData[packet.carID-1].driver == "") { s = packet.longData; eventData.driversData[packet.carID-1].driver = SeasonData::getInstance().getDriverName(s); //for every driver this code is executed only once since drivers list is sent only at the beginnig of the session //after whole list is updated, SeasonData singleton will contain fresh list of the main drivers that take a part in this session SeasonData::getInstance().updateTeamList(eventData.driversData[packet.carID-1]); //driver names are usually sent sorted, so after we got last driver we can reload helmets if (packet.carID == eventData.driversData.size()) ImagesFactory::getInstance().getHelmetsFactory().reloadHelmets(); } eventData.driversData[packet.carID-1].colorData.driverColor() = (LTPackets::Colors)packet.data; break; case LTPackets::CAR_POSITION_HISTORY: if (packet.length - 1 > eventData.lapsCompleted) eventData.lapsCompleted = copyPacket.length - 1; if (eventData.driversData[packet.carID-1].lapData.isEmpty()) eventData.driversData[packet.carID-1].lastLap.lapNum = copyPacket.length - 1; eventData.driversData[packet.carID-1].posHistory.clear(); for (int i = eventData.driversData[packet.carID-1].posHistory.size(); i < copyPacket.longData.size(); ++i) eventData.driversData[packet.carID-1].posHistory.append((int)copyPacket.longData[i]); //during the race carID is always equal to grid position if (eventData.eventType == LTPackets::RACE_EVENT && !eventData.driversData[packet.carID-1].posHistory.isEmpty()) eventData.driversData[packet.carID-1].posHistory[0] = packet.carID; break; default: switch (eventData.eventType) { case LTPackets::RACE_EVENT: handleRaceEvent(packet); break; case LTPackets::QUALI_EVENT: handleQualiEvent(packet); break; case LTPackets::PRACTICE_EVENT: handlePracticeEvent(packet); break; } } eventData.driversData[packet.carID-1].carID = packet.carID; if (emitSignal) emit driverDataChanged(packet.carID, dataUpdates); } void PacketParser::handleRaceEvent(const Packet &packet) { int lap = 0; PitData pd; switch (packet.type) { case LTPackets::RACE_GAP: if (packet.length > -1) { eventData.driversData[packet.carID-1].lastLap.gap = packet.longData; //after the start of the race we don't get the lap time so we have to add the lap here if (eventData.driversData[packet.carID-1].lapData.isEmpty() && eventData.driversData[packet.carID-1].posHistory.size() <= 1) { eventData.driversData[packet.carID-1].lastLap.lapNum = 1; eventData.driversData[packet.carID-1].addLap(eventData); } } eventData.driversData[packet.carID-1].colorData.gapColor() = (LTPackets::Colors)packet.data; //when driver is in the pits we need to update his position, gap and interval data if (eventData.driversData[packet.carID-1].lastLap.lapTime.toString() == "IN PIT") eventData.driversData[packet.carID-1].updateInPit(); break; case LTPackets::RACE_INTERVAL: if (eventData.driversData[packet.carID-1].pos == 1) { eventData.lapsCompleted = packet.longData.toInt(); eventData.saveWeather(); } if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.interval = packet.longData; if (eventData.driversData[packet.carID-1].pos == 1 && (eventData.driversData[packet.carID-1].lapData.isEmpty() && eventData.driversData[packet.carID-1].posHistory.size() <= 1)) { eventData.driversData[packet.carID-1].lastLap.lapNum = 1; eventData.driversData[packet.carID-1].addLap(eventData); } eventData.driversData[packet.carID-1].colorData.intervalColor() = (LTPackets::Colors)packet.data; //when driver is in the pits we need to update his position, gap and interval data if (eventData.driversData[packet.carID-1].lastLap.lapTime.toString() == "IN PIT") eventData.driversData[packet.carID-1].updateInPit(); break; case LTPackets::RACE_LAP_TIME: if (packet.length > -1) { eventData.driversData[packet.carID-1].lastLap.lapTime = LapTime(packet.longData.constData()); if (!eventData.driversData[packet.carID-1].lapData.isEmpty() && packet.longData != "OUT") eventData.driversData[packet.carID-1].lastLap.lapNum = eventData.driversData[packet.carID-1].lapData.last().lapNum + 1; if (eventData.driversData[packet.carID-1].lapData.isEmpty() && eventData.driversData[packet.carID-1].lastLap.lapTime.toString() == "IN PIT" && eventData.driversData[packet.carID-1].lastLap.lapNum < eventData.lapsCompleted) eventData.driversData[packet.carID-1].lastLap.lapNum++; eventData.driversData[packet.carID-1].addLap(eventData); } eventData.driversData[packet.carID-1].colorData.lapTimeColor() = (LTPackets::Colors)packet.data; if (eventData.driversData[packet.carID-1].lastLap.lapTime.toString() == "RETIRED") eventData.driversData[packet.carID-1].retired = true; else if (/*eventData.driversData[packet.carID-1].retired &&*/ eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString() != "STOP" && eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString() != "STOP" && eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString() != "STOP") eventData.driversData[packet.carID-1].retired = false; break; case LTPackets::RACE_SECTOR_1: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[0] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.sectorColor(1) = (LTPackets::Colors)packet.data; if ((LTPackets::Colors)packet.data == LTPackets::VIOLET) { if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString() != "") { eventData.sessionRecords.secRecord[0].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[0].lapTime = eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString(); eventData.sessionRecords.secRecord[0].number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.secRecord[0].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum + 1; } TrackRecords::getInstance().gatherSessionRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString() == "STOP" && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::RACE_PIT_LAP_1: lap = packet.longData.mid(1, packet.longData.size()-1).toInt(); if (lap != 0) { QString time; switch (eventData.driversData[packet.carID-1].numPits) { case 0: time = eventData.driversData[packet.carID-1].lastLap.sectorTimes[2]; break; case 1: time = eventData.driversData[packet.carID-1].lastLap.sectorTimes[1]; break; default: time = eventData.driversData[packet.carID-1].lastLap.sectorTimes[0]; break; } PitData pd(time, lap); eventData.driversData[packet.carID-1].addPitStop(pd); } eventData.driversData[packet.carID-1].colorData.pitColor(1) = (LTPackets::Colors)packet.data; dataUpdates.pitStopsUpdate = true; break; case LTPackets::RACE_SECTOR_2: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[1] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.sectorColor(2) = (LTPackets::Colors)packet.data; if ((LTPackets::Colors)packet.data == LTPackets::VIOLET) { if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString() != "") { eventData.sessionRecords.secRecord[1].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[1].lapTime = eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString(); eventData.sessionRecords.secRecord[1].number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.secRecord[1].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum+1; } TrackRecords::getInstance().gatherSessionRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString() == "STOP"/* && eventData.flagStatus != LTPackets::RED_FLAG*/) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::RACE_PIT_LAP_2: lap = packet.longData.mid(1, packet.longData.size()-1).toInt(); if (lap != 0) { QString time; switch (eventData.driversData[packet.carID-1].numPits) { case 1: time = eventData.driversData[packet.carID-1].lastLap.sectorTimes[2]; break; default: time = eventData.driversData[packet.carID-1].lastLap.sectorTimes[1]; break; } PitData pd(time, lap); eventData.driversData[packet.carID-1].addPitStop(pd); } eventData.driversData[packet.carID-1].colorData.pitColor(2) = (LTPackets::Colors)packet.data; dataUpdates.pitStopsUpdate = true; break; case LTPackets::RACE_SECTOR_3: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[2] = LapTime(packet.longData.constData()); //sector 3 time is sent after the lap time, therefore we have to update recently added lap eventData.driversData[packet.carID-1].updateLastLap(); eventData.driversData[packet.carID-1].colorData.sectorColor(3) = (LTPackets::Colors)packet.data; if ((LTPackets::Colors)packet.data == LTPackets::VIOLET && eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString() != "") { eventData.sessionRecords.secRecord[2].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[2].lapTime = eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString(); eventData.sessionRecords.secRecord[2].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum;//.driversData[packet.carID-1].lastLap.numLap); eventData.sessionRecords.secRecord[2].number = eventData.driversData[packet.carID-1].number; TrackRecords::getInstance().gatherSessionRecords(); eventData.driversData[packet.carID-1].updateSectorRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString() == "STOP" && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::RACE_PIT_LAP_3: lap = packet.longData.mid(1, packet.longData.size()-1).toInt(); pd = PitData(eventData.driversData[packet.carID-1].lastLap.sectorTimes[2], lap); eventData.driversData[packet.carID-1].addPitStop(pd); eventData.driversData[packet.carID-1].colorData.pitColor(3)= (LTPackets::Colors)packet.data; dataUpdates.pitStopsUpdate = true; break; case LTPackets::RACE_NUM_PITS: eventData.driversData[packet.carID-1].numPits = packet.longData.toInt(); eventData.driversData[packet.carID-1].colorData.numPitsColor() = (LTPackets::Colors)packet.data; break; default: break; } } void PacketParser::handleQualiEvent(const Packet &packet) { switch (packet.type) { case LTPackets::QUALI_PERIOD_1: eventData.driversData[packet.carID-1].qualiTimes[0] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].lastLap.lapTime = LapTime(packet.longData.constData()); if (eventData.driversData[packet.carID-1].pos == 1 && eventData.driversData[packet.carID-1].qualiTimes[0].isValid()) { if (eventData.driversData[packet.carID-1].qualiTimes[0] < eventData.sessionRecords.fastestLap.lapTime) { eventData.sessionRecords.fastestLap.lapTime = eventData.driversData[packet.carID-1].qualiTimes[0]; eventData.sessionRecords.fastestLap.number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.fastestLap.driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.fastestLap.qPeriod = 1; for (int i = 0; i < eventData.driversData.size(); ++i) eventData.driversData[i].updateGaps(eventData); TrackRecords::getInstance().gatherSessionRecords(); eventData.sessionRecords.qualiRecords[0] = eventData.driversData[packet.carID-1].qualiTimes[0]; } eventData.qualiPeriod = 1; } //correction of positions of drivers with time worse than 107% if (eventData.eventType == LTPackets::QUALI_EVENT && eventData.qualiPeriod == 1) { for (int i = 0; i < eventData.driversData.size(); ++i) { if (eventData.driversData[i].carID != packet.carID) eventData.driversData[i].correctPosition(eventData); } } eventData.driversData[packet.carID-1].colorData.qualiTimeColor(1) = (LTPackets::Colors)packet.data; break; case LTPackets::QUALI_PERIOD_2: eventData.driversData[packet.carID-1].lastLap.lapTime = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].qualiTimes[1] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.qualiTimeColor(2) = (LTPackets::Colors)packet.data; if (eventData.driversData[packet.carID-1].pos == 1 && eventData.driversData[packet.carID-1].qualiTimes[1].isValid()) { if (eventData.driversData[packet.carID-1].qualiTimes[1] < eventData.sessionRecords.fastestLap.lapTime) { eventData.sessionRecords.fastestLap.lapTime = eventData.driversData[packet.carID-1].qualiTimes[1]; eventData.sessionRecords.fastestLap.number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.fastestLap.driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.fastestLap.qPeriod = 2; for (int i = 0; i < eventData.driversData.size(); ++i) eventData.driversData[i].updateGaps(eventData); TrackRecords::getInstance().gatherSessionRecords(); eventData.sessionRecords.qualiRecords[1] = eventData.driversData[packet.carID-1].qualiTimes[1]; } eventData.qualiPeriod = 2; } break; case LTPackets::QUALI_PERIOD_3: eventData.driversData[packet.carID-1].lastLap.lapTime = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].qualiTimes[2] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.qualiTimeColor(3) = (LTPackets::Colors)packet.data; if (eventData.driversData[packet.carID-1].pos == 1 && eventData.driversData[packet.carID-1].qualiTimes[2].isValid()) { if (eventData.driversData[packet.carID-1].qualiTimes[2] < eventData.sessionRecords.fastestLap.lapTime) { eventData.sessionRecords.fastestLap.lapTime = eventData.driversData[packet.carID-1].qualiTimes[2]; eventData.sessionRecords.fastestLap.number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.fastestLap.driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.fastestLap.qPeriod = 3; for (int i = 0; i < eventData.driversData.size(); ++i) eventData.driversData[i].updateGaps(eventData); TrackRecords::getInstance().gatherSessionRecords(); eventData.sessionRecords.qualiRecords[2] = eventData.driversData[packet.carID-1].qualiTimes[2]; } eventData.qualiPeriod = 3; } break; case LTPackets::QUALI_SECTOR_1: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[0] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.sectorColor(1) = (LTPackets::Colors)packet.data; if ((LTPackets::Colors)packet.data == LTPackets::VIOLET) { if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString() != "" && eventData.driversData[packet.carID-1].lastLap.sectorTimes[0] <= LapTime(eventData.sessionRecords.secRecord[0].lapTime)) { eventData.sessionRecords.secRecord[0].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[0].lapTime = eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString(); eventData.sessionRecords.secRecord[0].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum; eventData.sessionRecords.secRecord[0].number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.secRecord[0].sessionTime = eventData.remainingTime; eventData.sessionRecords.secRecord[0].qPeriod = eventData.qualiPeriod; } TrackRecords::getInstance().gatherSessionRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString() == "STOP" && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::QUALI_SECTOR_2: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[1] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.sectorColor(2) =(LTPackets::Colors) packet.data; if ((LTPackets::Colors)packet.data == LTPackets::VIOLET) { if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString() != "" && eventData.driversData[packet.carID-1].lastLap.sectorTimes[1] <= LapTime(eventData.sessionRecords.secRecord[1].lapTime)) { eventData.sessionRecords.secRecord[1].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[1].lapTime = eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString(); eventData.sessionRecords.secRecord[1].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum; eventData.sessionRecords.secRecord[1].number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.secRecord[1].sessionTime = eventData.remainingTime; eventData.sessionRecords.secRecord[1].qPeriod = eventData.qualiPeriod; } TrackRecords::getInstance().gatherSessionRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString() == "STOP" && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::QUALI_SECTOR_3: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[2] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.sectorColor(3) = (LTPackets::Colors)packet.data; if ((LTPackets::Colors)packet.data == LTPackets::VIOLET) { if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString() != "" && eventData.driversData[packet.carID-1].lastLap.sectorTimes[2] <= LapTime(eventData.sessionRecords.secRecord[2].lapTime)) { eventData.sessionRecords.secRecord[2].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[2].lapTime = eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString(); eventData.sessionRecords.secRecord[2].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum; eventData.sessionRecords.secRecord[2].number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.secRecord[2].sessionTime = eventData.remainingTime; eventData.sessionRecords.secRecord[2].qPeriod = eventData.qualiPeriod; } TrackRecords::getInstance().gatherSessionRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString() == "STOP" && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::QUALI_LAP: eventData.driversData[packet.carID-1].lastLap.lapNum = packet.longData.toInt(); eventData.driversData[packet.carID-1].addLap(eventData); eventData.driversData[packet.carID-1].colorData.numLapsColor() = (LTPackets::Colors)packet.data; break; default: break; } } void PacketParser::handlePracticeEvent(const Packet &packet) { int ibuf; bool ok; switch (packet.type) { case LTPackets::PRACTICE_BEST: if (packet.length > 0) eventData.driversData[packet.carID-1].lastLap.lapTime = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.lapTimeColor() = (LTPackets::Colors)packet.data; if (eventData.driversData[packet.carID-1].pos == 1 && eventData.driversData[packet.carID-1].lastLap.lapTime.isValid() && eventData.driversData[packet.carID-1].lastLap.lapTime < eventData.sessionRecords.fastestLap.lapTime) { eventData.sessionRecords.fastestLap.lapTime = eventData.driversData[packet.carID-1].lastLap.lapTime; eventData.sessionRecords.fastestLap.number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.fastestLap.driver = eventData.driversData[packet.carID-1].driver; for (int i = 0; i < eventData.driversData.size(); ++i) eventData.driversData[i].updateGaps(eventData); TrackRecords::getInstance().gatherSessionRecords(); } break; case LTPackets::PRACTICE_GAP: if (packet.length > 0) eventData.driversData[packet.carID-1].lastLap.gap = packet.longData; eventData.driversData[packet.carID-1].colorData.gapColor() = (LTPackets::Colors)packet.data; break; case LTPackets::PRACTICE_SECTOR_1: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[0] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.sectorColor(1) = (LTPackets::Colors)packet.data; //save the session fastest sector 1 time if ((LTPackets::Colors)packet.data == LTPackets::VIOLET) { if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString() != "") { eventData.sessionRecords.secRecord[0].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[0].lapTime = LapTime(packet.longData.constData()); eventData.sessionRecords.secRecord[0].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum; eventData.sessionRecords.secRecord[0].number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.secRecord[0].sessionTime = eventData.remainingTime; } TrackRecords::getInstance().gatherSessionRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[0].toString() == "STOP" && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::PRACTICE_SECTOR_2: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[1] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.sectorColor(2) = (LTPackets::Colors)packet.data; //save the session fastest sector 2 time if ((LTPackets::Colors)packet.data == LTPackets::VIOLET) { if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString() != "") { eventData.sessionRecords.secRecord[1].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[1].lapTime = LapTime(packet.longData.constData()); eventData.sessionRecords.secRecord[1].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum; eventData.sessionRecords.secRecord[1].number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.secRecord[1].sessionTime = eventData.remainingTime; } TrackRecords::getInstance().gatherSessionRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[1].toString() == "STOP" && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::PRACTICE_SECTOR_3: if (packet.length > -1) eventData.driversData[packet.carID-1].lastLap.sectorTimes[2] = LapTime(packet.longData.constData()); eventData.driversData[packet.carID-1].colorData.sectorColor(3) = (LTPackets::Colors)packet.data; //save the session fastest sector 3 time if ((LTPackets::Colors)packet.data == LTPackets::VIOLET) { if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString() != "") { eventData.sessionRecords.secRecord[2].driver = eventData.driversData[packet.carID-1].driver; eventData.sessionRecords.secRecord[2].lapTime = eventData.driversData[packet.carID-1].lastLap.sectorTimes[2]; eventData.sessionRecords.secRecord[2].lapNum = eventData.driversData[packet.carID-1].lastLap.lapNum; eventData.sessionRecords.secRecord[2].number = eventData.driversData[packet.carID-1].number; eventData.sessionRecords.secRecord[2].sessionTime = eventData.remainingTime; } TrackRecords::getInstance().gatherSessionRecords(); } if (eventData.driversData[packet.carID-1].lastLap.sectorTimes[2].toString() == "STOP" && eventData.flagStatus != LTPackets::RED_FLAG) eventData.driversData[packet.carID-1].retired = true; break; case LTPackets::PRACTICE_LAP: ibuf = packet.longData.toInt(&ok); if (ok && ibuf > 0) eventData.driversData[packet.carID-1].lastLap.lapNum = ibuf; eventData.driversData[packet.carID-1].addLap(eventData); eventData.driversData[packet.carID-1].colorData.numLapsColor() = (LTPackets::Colors)packet.data; break; default: break; } } void PacketParser::clearBuffer() { packetBuffer->clear(); } void PacketParser::parseSystemPacket(Packet &packet, bool emitSignal) { // if (/*packet.type != LTPackets::SYS_COMMENTARY &&*/ packet.type != LTPackets::SYS_TIMESTAMP) // qDebug()<<"SYS="<<packet.type<<" "<<packet.carID<<" "<<packet.data<<" "<<packet.length<<" "<< (/*(packet.type != LTPackets::SYS_COMMENTARY) ?*/ packet.longData.constData() /*: ""*/); unsigned int number, i; // unsigned char packetLongData[129]; unsigned char uc; QString s, format, oldTime; QTime time; int ibuf; double dbuf; bool ok; int j = 0; int cnt; Packet copyPacket = packet; // if (packet.type != LTPackets::SYS_COMMENTARY && packet.type != LTPackets::SYS_KEY_FRAME && !decrypter.checkDecryption(packet.longData)) // { // packet.longData = ""; // packet.length = 0; //// eventData.frame = 0; // } if (eventData.eventType == LTPackets::QUALI_EVENT && eventData.qualiPeriod == 0) eventData.qualiPeriod = 1; switch(packet.type) { case LTPackets::SYS_EVENT_ID: number = 0; //just before the start of the session server sends a strange packet with the current data instead of the number of decryption key that we have to obtain number = copyPacket.longData.right(copyPacket.longData.size()-1).toInt(&ok); s = copyPacket.longData.right(copyPacket.longData.size()-1); eventData.key = 0; decrypter.key = 0; if (ok) { eventData.eventId = number; emit requestDecryptionKey(number); } else eventData.frame = 0; if (eventData.eventType != 0 && eventData.eventType != (LTPackets::EventType)packet.data) eventData.clear(); if (s.size() > 0 && s[0] == '_') { eventData.clear(); noSession = true; emit noLiveSession(true, s.right(s.size()-1)); } eventData.eventInfo = SeasonData::getInstance().getEvent(/*QDate::fromString("18.11.2012", "dd.MM.yyyy"));*/QDate::currentDate());//(int)(packet.longData[0]); eventData.eventType = (LTPackets::EventType)copyPacket.data; eventData.lapsCompleted = 0; break; case LTPackets::SYS_KEY_FRAME: number = 0; i = packet.length; while(i) { number <<= 8; uc = packet.longData[--i]; number |= uc; } if (!eventData.frame || number == 1) // || decryption_failure { eventData.frame = number; emit requestKeyFrame(number); // decryptionKeyObtained(2841044872); //valencia race // decryptionKeyObtained(2971732062); //valencia qual // decryptionKeyObtained(3230237603); //valencia fp1 // onDecryptionKeyObtained(3585657959); //? // onDecryptionKeyObtained(2488580439); //qual // onDecryptionKeyObtained(2438680630); //race // onDecryptionKeyObtained(3875488254); //fp1 // onDecryptionKeyObtained(2991040326); //bahrain fp2 // onDecryptionKeyObtained(2976363859); //bahrain fp3 // onDecryptionKeyObtained(2462388168); //bahrain quali // onDecryptionKeyObtained(2942703366); //bahrain race // onDecryptionKeyObtained(3710001497); //malaysia race // onDecryptionKeyObtained(2922444379); //spain race // httpReader.obtainKeyFrame(53); // onDecryptionKeyObtained(4246644581); //gbr race // decryptionKeyObtained(3195846070); //gbr quali // onDecryptionKeyObtained(3397635038); //gbr fp3 // onDecryptionKeyObtained(4071769653); //gbr fp1 } else eventData.frame = number; break; case LTPackets::SYS_WEATHER: switch (packet.data) { case LTPackets::WEATHER_SESSION_CLOCK: s = packet.longData; cnt = s.count(':'); oldTime = eventData.remainingTime.toString("mm:ss"); format = (cnt == 2) ? "h:mm:ss" : "mm:ss"; time = QTime::fromString(s, format); if (time.isValid()) eventData.remainingTime = time; if (oldTime == "00:00" && time.minute() != 0 && eventData.eventType == LTPackets::QUALI_EVENT) ++eventData.qualiPeriod; //session actually starts when we get the 59 seconds mark (i.e. Q1 starts when the time is 19:59) j = eventData.remainingTime.second(); if ((!eventData.sessionStarted || eventData.qualiBreak) && j != 0 && (eventData.eventType != LTPackets::RACE_EVENT || (eventData.eventType == LTPackets::RACE_EVENT && eventData.lapsCompleted < eventData.eventInfo.laps)) && !eventData.isFridayBeforeFP1()) { eventData.sessionStarted = true; eventData.qualiBreak = false; eventData.sessionFinished = false; } emit sessionStarted(); break; case LTPackets::WEATHER_TRACK_TEMP: number = 0; dbuf = packet.longData.toDouble(&ok); if (ok) { eventData.weather.setTrackTemp(dbuf); eventData.saveWeather(); } dataUpdates.weatherUpdate = true; break; case LTPackets::WEATHER_AIR_TEMP: dbuf = packet.longData.toDouble(&ok); if (ok) { eventData.weather.setAirTemp(dbuf); eventData.saveWeather(); } dataUpdates.weatherUpdate = true; break; case LTPackets::WEATHER_WIND_SPEED: dbuf = packet.longData.toDouble(&ok); if (ok) { eventData.weather.setWindSpeed(dbuf); eventData.saveWeather(); } dataUpdates.weatherUpdate = true; break; case LTPackets::WEATHER_HUMIDITY: dbuf = packet.longData.toDouble(&ok); if (ok) { eventData.weather.setHumidity(dbuf); eventData.saveWeather(); } dataUpdates.weatherUpdate = true; break; case LTPackets::WEATHER_PRESSURE: number = 0; dbuf = packet.longData.toDouble(&ok); if (ok) { eventData.weather.setPressure(dbuf); eventData.saveWeather(); } dataUpdates.weatherUpdate = true; break; case LTPackets::WEATHER_WIND_DIRECTION: dbuf = packet.longData.toDouble(&ok); if (ok) { eventData.weather.setWindDirection(dbuf); eventData.saveWeather(); } dataUpdates.weatherUpdate = true; break; case LTPackets::WEATHER_WET_TRACK: ibuf = packet.longData.toInt(&ok); if (ok) { eventData.weather.setWetDry(ibuf); eventData.saveWeather(); } dataUpdates.weatherUpdate = true; break; default: break; } break; case LTPackets::SYS_TRACK_STATUS: switch (packet.data) { case 1: uc = packet.longData[0]; eventData.flagStatus = LTPackets::FlagStatus(uc - '0'); break; } break; case LTPackets::SYS_COPYRIGHT: break; case LTPackets::SYS_NOTICE: break; case LTPackets::SYS_SPEED: dataUpdates.speedRecordsUpdate = true; switch((int)copyPacket.longData[0]) { case LTPackets::SPEED_SECTOR1: for (int i = 1, j=0; i < copyPacket.longData.size() && j < 6; i+=8) { eventData.sessionRecords.secSpeed[0][j].driver = SeasonData::getInstance().getDriverNameFromShort(copyPacket.longData.mid(i, 3)); eventData.sessionRecords.secSpeed[0][j++].speed = copyPacket.longData.mid(i+4, 3).toDouble(); } break; case LTPackets::SPEED_SECTOR2: for (int i = 1, j=0; i < copyPacket.longData.size() && j < 6; i+=8) { eventData.sessionRecords.secSpeed[1][j].driver = SeasonData::getInstance().getDriverNameFromShort(copyPacket.longData.mid(i, 3)); eventData.sessionRecords.secSpeed[1][j++].speed = copyPacket.longData.mid(i+4, 3).toDouble(); } break; case LTPackets::SPEED_SECTOR3: for (int i = 1, j=0; i < copyPacket.longData.size() && j < 6; i+=8) { eventData.sessionRecords.secSpeed[2][j].driver = SeasonData::getInstance().getDriverNameFromShort(copyPacket.longData.mid(i, 3)); eventData.sessionRecords.secSpeed[2][j++].speed = copyPacket.longData.mid(i+4, 3).toDouble(); } break; case LTPackets::SPEED_TRAP: for (int i = 1, j=0; i < copyPacket.longData.size() && j < 6; i+=8) { eventData.sessionRecords.speedTrap[j].driver = SeasonData::getInstance().getDriverNameFromShort(copyPacket.longData.mid(i, 3)); eventData.sessionRecords.speedTrap[j++].speed = copyPacket.longData.mid(i+4, 3).toDouble(); } break; case LTPackets::FL_CAR: if(eventData.eventType == LTPackets::RACE_EVENT) eventData.sessionRecords.fastestLap.number = copyPacket.longData.mid(1, copyPacket.longData.size()-1).toInt(); break; case LTPackets::FL_DRIVER: if (eventData.eventType == LTPackets::RACE_EVENT) { s = copyPacket.longData.mid(1, copyPacket.longData.size()-1); eventData.sessionRecords.fastestLap.driver = SeasonData::getInstance().getDriverName(s);// s.left(4) + s.right(s.size()-4).toLower(); } break; case LTPackets::FL_LAP: eventData.sessionRecords.fastestLap.lapNum = copyPacket.longData.mid(1, copyPacket.longData.size()-1).toInt(); if (eventData.sessionRecords.fastestLap.lapNum > 0) { for (int i = 0; i < eventData.driversData.size(); ++i) { if (eventData.driversData[i].number == eventData.sessionRecords.fastestLap.number) { eventData.driversData[i].setFastestLap(eventData.sessionRecords.fastestLap.lapTime, eventData.sessionRecords.fastestLap.lapNum); break; } } } break; case LTPackets::FL_TIME: if (eventData.eventType == LTPackets::RACE_EVENT) eventData.sessionRecords.fastestLap.lapTime = LapTime(copyPacket.longData.mid(1, copyPacket.longData.size()-1).constData()); TrackRecords::getInstance().gatherSessionRecords(); break; } break; case LTPackets::SYS_COMMENTARY: dataUpdates.commentaryUpdate = true; s = copyPacket.longData.mid(2, copyPacket.longData.size()-2); if ((int)copyPacket.longData[0] < 32) { if ((int)(copyPacket.longData[1] & 2) > 0) eventData.commentary.append(s); else eventData.commentary.append(QString::fromUtf8(s.toAscii())); } else eventData.commentary.append(s.toLatin1()); //second byte of the commentary tells wether we need to append new line if ((int)(copyPacket.longData[1])) eventData.commentary.append("\n\n"); case LTPackets::SYS_TIMESTAMP: { uc = copyPacket.longData[1]; int ts = uc << 8; uc = copyPacket.longData[0]; ts |= uc | 0 << 16; } break; default: break; } if (emitSignal) emit eventDataChanged(dataUpdates); } void PacketParser::parsePackets(const QVector<Packet> &packets) { // dataUpdates.setAllFalse(); for (int i = 0; i < packets.size(); ++i) { Packet packet = packets[i]; if (packet.carID) parseCarPacket(packet, false); else if (packet.type > 2) parseSystemPacket(packet, false); else if (packet.type == 1) { eventData.eventType = (LTPackets::EventType)packet.data; // eventData.eventInfo = LTPackets::getEvent(QDate::currentDate()); eventData.lapsCompleted = 0; } } emit dataChanged(dataUpdates); } void PacketParser::parseBufferedPackets(const QVector<QPair<Packet, qint64> > &packets) { dataUpdates.setAllFalse(); // bool emitSignal = false; for (int i = 0; i < packets.size(); ++i) { // if (i == packets.size() - 1) // emitSignal = true; Packet packet = packets[i].first; if (packet.carID) parseCarPacket(packet, false); else parseSystemPacket(packet, false); emit packetParsed(packets[i]); } emit dataChanged(dataUpdates); } void PacketParser::parseBufferedPackets(const QPair<Packet, qint64> &packetPair) { dataUpdates.setAllFalse(); Packet copyPacket = packetPair.first; if (copyPacket.carID) parseCarPacket(copyPacket, true); else parseSystemPacket(copyPacket, true); emit packetParsed(packetPair); } void PacketParser::streamBlockObtained(const QByteArray &buf) { savePacket(buf); if (parsing) streamData.append(buf); else parseStreamBlock(buf); } void PacketParser::keyFrameObtained(const QByteArray &keyFrame) { //streamData = keyFrame; savePacket(keyFrame); decrypter.resetDecryption(); if (parsing) { streamData.append(keyFrame); } else { clearEncryptedPackets(); // parseStreamBlock(keyFrame); parseKeyFrame(keyFrame); } } void PacketParser::decryptionKeyObtained(unsigned int key) { eventData.key = key; decrypter.key = key; if (key == 0) return; for (int i = 0; i < encryptedPackets.size(); ++i) { decrypter.decrypt(encryptedPackets[i].longData); if(encryptedPackets[i].carID) parseCarPacket(encryptedPackets[i], true); else parseSystemPacket(encryptedPackets[i], false); } encryptedPackets.clear(); dataUpdates.setAllTrue(); emit dataChanged(dataUpdates); } void PacketParser::savePacket(const QByteArray &) { //QFile file(QString("packets/packet_%1.dat").arg(packetNo++)); //if (file.open(QIODevice::WriteOnly)) //file.write(buf); }
zywhlc-f1lt
src/net/packetparser.cpp
C++
gpl3
58,592
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef HttpDataReader_H #define HttpDataReader_H #include <QObject> #include <QNetworkAccessManager> #include <QNetworkCookie> #include <QNetworkRequest> #include <QNetworkReply> class HttpDataReader : public QObject { Q_OBJECT public: explicit HttpDataReader(QObject *parent = 0); ~HttpDataReader(); void authorize(); QString getCookie() { return cookie; } bool parseCookie(QString header); signals: void cookieRecieved(QString cookie); void keyFrameObtained(const QByteArray &); void decryptionKeyObtained(unsigned int); void authorizationError(); void error(QNetworkReply::NetworkError); public slots: void finished(); void obtainKeyFrame(unsigned int frame); void obtainDecryptionKey(unsigned int event_no); private: QNetworkAccessManager manager; QNetworkRequest req; QNetworkReply *reply; QString cookie; QByteArray keyFrame; unsigned int decryptionKey; long bytes; int state; //0 - doing nothing, 1 - authorizing, 2 - obtaining key frame, 3 - obtaining decryption key }; #endif // HttpDataReader_H
zywhlc-f1lt
src/net/httpdatareader.h
C++
gpl3
2,661
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef PACKETBUFFER_H #define PACKETBUFFER_H #include <QObject> #include <QPair> #include <QQueue> #include <QTimer> #include "packetparser.h" class PacketBuffer : public QObject { Q_OBJECT public: explicit PacketBuffer(PacketParser *parser, QObject *parent = 0); void addPacket(Packet &); bool hasToBeBuffered(); void clear() { timer->stop(); packetsQueue.clear(); } signals: public slots: void timeout(); void setDelay(int); private: int delay; QTimer *timer; QQueue< QPair<Packet, qint64> > packetsQueue; PacketParser *packetParser; }; #endif // PACKETBUFFER_H
zywhlc-f1lt
src/net/packetbuffer.h
C++
gpl3
2,198
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "packetbuffer.h" #include "packetparser.h" #include <QDebug> PacketBuffer::PacketBuffer(PacketParser *parser, QObject *parent) : QObject(parent), delay(0), packetParser(parser) { timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(timeout())); } void PacketBuffer::addPacket(Packet &packet) { if (delay == 0) packetParser->parseBufferedPackets(qMakePair(packet, QDateTime::currentMSecsSinceEpoch())); else packetsQueue.enqueue(qMakePair(packet, QDateTime::currentMSecsSinceEpoch())); } bool PacketBuffer::hasToBeBuffered() { if (delay == 0) { timeout(); return false; } return true; } void PacketBuffer::timeout() { qint64 currTime = QDateTime::currentMSecsSinceEpoch() - delay * 1000; QVector< QPair<Packet, qint64> > packetsToHandle; while (!packetsQueue.isEmpty()) { if (packetsQueue.head().second <= currTime) packetsToHandle.append(packetsQueue.dequeue()); else break; } packetParser->parseBufferedPackets(packetsToHandle); } void PacketBuffer::setDelay(int del) { delay = del; if (delay != 0 && !timer->isActive()) timer->start(100); else if (delay == 0 && timer->isActive()) { timer->stop(); timeout(); } }
zywhlc-f1lt
src/net/packetbuffer.cpp
C++
gpl3
2,871
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "httpdatareader.h" #include <QDebug> #include <QFile> #include <QTextStream> #include "networksettings.h" HttpDataReader::HttpDataReader(QObject *parent) : QObject(parent), state(0) { bytes = 0; } HttpDataReader::~HttpDataReader() { qDebug()<<"HTTP bytes received = "<<bytes; } void HttpDataReader::authorize() { QString authHost = NetworkSettings::getInstance().getHttpLoginUrl() + ""; QString content("application/x-www-form-urlencoded"); QByteArray bArray(QString("email="+NetworkSettings::getInstance().getUser() + "&password=" + NetworkSettings::getInstance().getPassword()).toAscii()); if (NetworkSettings::getInstance().usingProxy()) manager.setProxy(NetworkSettings::getInstance().getProxy()); else manager.setProxy(QNetworkProxy::NoProxy); req = QNetworkRequest(authHost); req.setHeader(QNetworkRequest::ContentTypeHeader, content.toAscii()); req.setHeader(QNetworkRequest::ContentLengthHeader, QVariant(bArray.size()).toString()); req.setRawHeader("User-Agent","f1lt"); reply = manager.post(req, bArray); state = 1; connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); connect(reply, SIGNAL(finished()), this, SLOT(finished())); } void HttpDataReader::obtainKeyFrame(unsigned int frame) { if (state != 0) return; QString keyhost = NetworkSettings::getInstance().getHttpKeyFrameUrl(); if (frame > 0) { QString k = QString("%1").arg(frame); int size = k.size(); for (int i = 0; i < 5 - size; ++i) { k = "0" + k; } keyhost += "_" + k; } keyhost += ".bin"; req = QNetworkRequest(keyhost); req.setRawHeader("User-Agent","f1lt"); reply = manager.get(req); state = 2; qDebug(keyhost.toStdString().c_str()); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); connect(reply, SIGNAL(finished()), this, SLOT(finished())); } void HttpDataReader::obtainDecryptionKey(unsigned int event_no) { QString keyhost = NetworkSettings::getInstance().getHttpDecryptionKeyUrl() + QString("%1").arg(event_no) + ".asp?auth=" + cookie; req = QNetworkRequest(keyhost); req.setRawHeader("User-Agent","f1lt"); reply = manager.get(req); state = 3; qDebug(keyhost.toStdString().c_str()); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); connect(reply, SIGNAL(finished()), this, SLOT(finished())); } void HttpDataReader::finished() { if (state == 1) { QString v = qvariant_cast<QString>(reply->rawHeader("Set-Cookie")); state = 0; if (parseCookie(v)) emit cookieRecieved(cookie); } else if (state == 2) { keyFrame = reply->readAll(); bytes += keyFrame.size(); state = 0; emit keyFrameObtained(keyFrame); } else if (state == 3) { QByteArray buf = reply->readAll(); decryptionKey = 0; bytes += buf.size(); for (int i = 0; i < buf.size(); ++i) { if ((buf[i] >= '0') && (buf[i] <= '9')) decryptionKey = (decryptionKey << 4) | (buf[i] - '0'); else if ((buf[i] >= 'a') && (buf[i] <= 'f')) decryptionKey = (decryptionKey << 4) | (buf[i] - 'a' + 10); else if ((buf[i] >= 'A') && (buf[i] <= 'F')) decryptionKey = (decryptionKey << 4) | (buf[i] - 'A' + 10); else break; } state = 0; emit decryptionKeyObtained(decryptionKey); } } bool HttpDataReader::parseCookie(QString header) { int idx = header.indexOf("USER="); if (idx == -1) { emit authorizationError(); return false; } idx += 5; int idx2 = header.indexOf(";"); cookie = header.right(header.length() - idx).left(idx2-idx); return true; }
zywhlc-f1lt
src/net/httpdatareader.cpp
C++
gpl3
5,611
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef NETWORKSETTINGS_H #define NETWORKSETTINGS_H #include <QNetworkProxy> #include <QSettings> #include <QString> class NetworkSettings { public: static NetworkSettings &getInstance() { static NetworkSettings instance; return instance; } QString getUser() { return user; } void setUserPassword(QString u, QString p) { user = u; passwd = encodePasswd(p); } QString getPassword() { return encodePasswd(passwd); } QString getHttpHost() { return httpHost; } QString getHttpLoginUrl() { return httpLoginUrl; } QString getHttpKeyFrameUrl() { return httpKeyFrameUrl; } QString getHttpDecryptionKeyUrl() { return httpDecryptionKeyUrl; } QString getSocketHost() { return socketHost; } int getSocketPort() { return socketPort; } QString getLTDataUrl() { return ltDataUrl; } QString getLTDataList() { return ltDataList; } QString getVersionUrl() { return versionUrl; } bool usingProxy() { return proxyOn; } QNetworkProxy getProxy() { return proxy; } void setProxy(const QNetworkProxy &p, bool pOn = false) { proxy = p; proxyOn = pOn; } void loadSettings(const QSettings &settings); void saveSettings(QSettings &settings); private: NetworkSettings(); //very simple passwd encoding algorithm QString encodePasswd(QString passwd) { int sz = passwd.size(); QString ret; for (int i = 0; i < sz; ++i) { char c = passwd[i].toAscii(); c ^= (1 << (i%8)); ret += c; } return ret; } QString user; QString passwd; QString httpHost; QString httpLoginUrl; QString httpKeyFrameUrl; QString httpDecryptionKeyUrl; QString socketHost; int socketPort; QString ltDataUrl; QString ltDataList; QString versionUrl; bool proxyOn; QNetworkProxy proxy; }; #endif // NETWORKSETTINGS_H
zywhlc-f1lt
src/net/networksettings.h
C++
gpl3
3,729
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef SocketDataReader_H #define SocketDataReader_H #include <QObject> #include <QThread> #include <QTcpSocket> #include <QTimer> class SocketDataReader : public QObject { Q_OBJECT public: void runS(); SocketDataReader(QObject *parent=0); ~SocketDataReader(); void openStream(); void connectToHost(); void disconnectFromHost(); void wakeUpServer(); signals: void streamOpened(); void packetObtained(const QByteArray &); void error(QAbstractSocket::SocketError); public slots: void connected(); void readyRead(); void timeout(); void connectionError(QAbstractSocket::SocketError); void reconnect(); private: QTcpSocket *socket; QByteArray data; QTimer *timer; QTimer *reconnectTimer; bool connectionOpened; int tryReconnect; long bytes; }; #endif // SocketDataReader_H
zywhlc-f1lt
src/net/socketdatareader.h
C++
gpl3
2,421
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LTFILESMANAGER_H #define LTFILESMANAGER_H #include <QNetworkAccessManager> #include <QNetworkRequest> #include <QNetworkReply> #include <QStringList> #include <QObject> class LTFilesManager : public QObject { Q_OBJECT public: explicit LTFilesManager(QObject *parent = 0); signals: void ltListObtained(QStringList); void ltFileObtained(QByteArray); void downloadProgress ( qint64 bytesReceived, qint64 bytesTotal ); void error ( QNetworkReply::NetworkError code ); public slots: void getLTList(); void getLTFile(QString); void cancel(); void finishedLTList(); void finishedLTFile(); private: QNetworkAccessManager manager; QNetworkRequest req; QNetworkReply *reply; }; #endif // LTFILESMANAGER_H
zywhlc-f1lt
src/net/ltfilesmanager.h
C++
gpl3
2,322
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "ltfilesmanager.h" #include <QByteArray> #include <QDebug> #include "networksettings.h" LTFilesManager::LTFilesManager(QObject *parent) : QObject(parent) { } void LTFilesManager::getLTList() { req = QNetworkRequest(NetworkSettings::getInstance().getLTDataList()); req.setRawHeader("User-Agent","f1lt"); if (NetworkSettings::getInstance().usingProxy()) manager.setProxy(NetworkSettings::getInstance().getProxy()); else manager.setProxy(QNetworkProxy::NoProxy); reply = manager.get(req); connect(reply, SIGNAL(finished()), this, SLOT(finishedLTList())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); } void LTFilesManager::getLTFile(QString ltDataFile) { req = QNetworkRequest(NetworkSettings::getInstance().getLTDataUrl() + ltDataFile); req.setRawHeader("User-Agent","f1lt"); reply = manager.get(req); connect(reply, SIGNAL(finished()), this, SLOT(finishedLTFile())); connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SIGNAL(downloadProgress(qint64,qint64))); } void LTFilesManager::finishedLTList() { QString buf = reply->readAll().constData(); QStringList ltList = buf.split("<br>"); disconnect(reply, SIGNAL(finished()), this, SLOT(finishedLTFile())); disconnect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); emit ltListObtained(ltList); } void LTFilesManager::finishedLTFile() { QByteArray buf = reply->readAll(); disconnect(reply, SIGNAL(finished()), this, SLOT(finishedLTList())); disconnect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); disconnect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SIGNAL(downloadProgress(qint64,qint64))); emit ltFileObtained(buf); } void LTFilesManager::cancel() { if (reply) { reply->close(); manager.deleteResource(req); } }
zywhlc-f1lt
src/net/ltfilesmanager.cpp
C++
gpl3
3,694
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef DATASTREAMREADER_H #define DATASTREAMREADER_H #include <QObject> #include <QFile> #include <QList> #include <iostream> #include "../core/eventdata.h" #include "httpdatareader.h" #include "packetparser.h" #include "socketdatareader.h" //#include <httpconnection.h> class DataStreamReader : public QObject { Q_OBJECT public: explicit DataStreamReader(QObject *parent = 0); void connectToLTServer(); void disconnectFromLTServer(); bool parsePacket(const QByteArray&, Packet &packet, int &pos); void parseCarPacket(Packet &packet, bool emitSignal = true); void parseSystemPacket(Packet &packet, bool emitSignal = true); // void run(); signals: void streamOpened(); void tryAuthorize(); void authorized(QString); void sessionStarted(); void authorizationError(); void error(QAbstractSocket::SocketError); void error(QNetworkReply::NetworkError); void noLiveSession(bool, QString); void packetParsed(const Packet&); void packetParsed(const QPair<Packet, qint64>&); void eventDataChanged(const DataUpdates &); void driverDataChanged(int id, const DataUpdates &); void dataChanged(const DataUpdates &); public slots: //void connected(); //void error(QAbstractSocket::SocketError); void clearData(); void onCookieReceived(QString); void parsePackets(const QVector<Packet> &); void setDelay(int prevDelay, int delay); private: SocketDataReader socketReader; HttpDataReader httpReader; PacketParser parser; EventData &eventData; }; #endif // DATASTREAMREADER_H
zywhlc-f1lt
src/net/datastreamreader.h
C++
gpl3
3,159
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "socketdatareader.h" #include <QDebug> #include "networksettings.h" SocketDataReader::SocketDataReader(QObject *parent) : QObject(parent), connectionOpened(false) { timer = new QTimer(this); reconnectTimer = new QTimer(this); QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timeout())); bytes = 0; socket = NULL; } SocketDataReader::~SocketDataReader() { qDebug()<<"Bytes received: "<<bytes; } void SocketDataReader::openStream() { if (connectionOpened) return; tryReconnect = 5; // if (!isRunning()) // start(); // else // connectToHost(); runS(); } void SocketDataReader::connectToHost() { if (NetworkSettings::getInstance().usingProxy() && NetworkSettings::getInstance().getProxy().type() == QNetworkProxy::Socks5Proxy) socket->setProxy(NetworkSettings::getInstance().getProxy()); else socket->setProxy(QNetworkProxy::NoProxy); socket->connectToHost(NetworkSettings::getInstance().getSocketHost(), NetworkSettings::getInstance().getSocketPort(), QIODevice::ReadWrite); socket->waitForReadyRead(); } void SocketDataReader::disconnectFromHost() { if (socket && socket->isOpen()) socket->disconnectFromHost(); timer->stop(); connectionOpened = false; if (socket) { QObject::disconnect(socket, SIGNAL(connected()), this, SLOT(connected())); QObject::disconnect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError))); QObject::disconnect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); } if (reconnectTimer) QObject::disconnect(reconnectTimer, SIGNAL(timeout()), this, SLOT(reconnect())); } void SocketDataReader::wakeUpServer() { char wbuf[1]; wbuf[0] = 0x10; socket->write(wbuf, sizeof(wbuf)); } void SocketDataReader::runS() { socket = new QTcpSocket(); QObject::connect(socket, SIGNAL(connected()), this, SLOT(connected())); QObject::connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError))); QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); QObject::connect(reconnectTimer, SIGNAL(timeout()), this, SLOT(reconnect())); connectionOpened = false; connectToHost(); } void SocketDataReader::connected() { connectionOpened = true; if (reconnectTimer->isActive()) { reconnectTimer->stop(); } timer->start(1000); tryReconnect = 5; emit streamOpened(); } void SocketDataReader::readyRead() { QByteArray pac = socket->readAll(); bytes += pac.size(); emit packetObtained(pac); } void SocketDataReader::timeout() { wakeUpServer(); } void SocketDataReader::connectionError(QAbstractSocket::SocketError err) { timer->stop(); if (tryReconnect == 5) { reconnect(); } else if (tryReconnect == 0) { if (reconnectTimer->isActive()) reconnectTimer->stop(); emit error(err); } } void SocketDataReader::reconnect() { if (tryReconnect == 5) { --tryReconnect; reconnectTimer->start(500); } else if (tryReconnect > 0) { if (socket && socket->isOpen()) socket->disconnectFromHost(); connectionOpened = false; --tryReconnect; connectToHost(); } else if (reconnectTimer->isActive()) reconnectTimer->stop(); }
zywhlc-f1lt
src/net/socketdatareader.cpp
C++
gpl3
4,962
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "datastreamreader.h" #include <cmath> #include <QDebug> #include <QFile> #include <QTextStream> #include <QRegExp> #include "networksettings.h" DataStreamReader::DataStreamReader(QObject *parent) : QObject(parent), eventData(EventData::getInstance()) { connect(&httpReader, SIGNAL(cookieRecieved(QString)), this, SLOT(onCookieReceived(QString))); connect(&httpReader, SIGNAL(keyFrameObtained(QByteArray)), &parser, SLOT(keyFrameObtained(QByteArray))); connect(&httpReader, SIGNAL(decryptionKeyObtained(uint)), &parser, SLOT(decryptionKeyObtained(uint))); connect(&httpReader, SIGNAL(authorizationError()), this, SIGNAL(authorizationError())); connect(&httpReader, SIGNAL(error(QNetworkReply::NetworkError)), this, SIGNAL(error(QNetworkReply::NetworkError))); connect(&socketReader, SIGNAL(packetObtained(QByteArray)), &parser, SLOT(streamBlockObtained(QByteArray))); connect(&socketReader, SIGNAL(error(QAbstractSocket::SocketError)), this, SIGNAL(error(QAbstractSocket::SocketError))); connect(&parser, SIGNAL(noLiveSession(bool,QString)), this, SIGNAL(noLiveSession(bool,QString))); connect(&parser, SIGNAL(sessionStarted()), this, SIGNAL(sessionStarted())); connect(&parser, SIGNAL(packetParsed(Packet)), this, SIGNAL(packetParsed(Packet))); connect(&parser, SIGNAL(packetParsed(QPair<Packet, qint64>)), this, SIGNAL(packetParsed(QPair<Packet, qint64>))); connect(&parser, SIGNAL(eventDataChanged(const DataUpdates &)), this, SIGNAL(eventDataChanged(const DataUpdates &))); connect(&parser, SIGNAL(driverDataChanged(int, const DataUpdates &)), this, SIGNAL(driverDataChanged(int, const DataUpdates &))); connect(&parser, SIGNAL(dataChanged(const DataUpdates &)), this, SIGNAL(dataChanged(const DataUpdates &))); connect(&parser, SIGNAL(requestKeyFrame(uint)), &httpReader, SLOT(obtainKeyFrame(uint))); connect(&parser, SIGNAL(requestDecryptionKey(uint)), &httpReader, SLOT(obtainDecryptionKey(uint))); } void DataStreamReader::setDelay(int prevDelay, int delay) { parser.setDelay(prevDelay, delay); } void DataStreamReader::connectToLTServer() { eventData.frame = 0; emit tryAuthorize(); httpReader.authorize(); } void DataStreamReader::disconnectFromLTServer() { socketReader.disconnectFromHost(); parser.clearBuffer(); } void DataStreamReader::onCookieReceived(QString cookie) { eventData.cookie = cookie; socketReader.openStream(); emit authorized(cookie); } void DataStreamReader::clearData() { parser.clearData(); } void DataStreamReader::parsePackets(const QVector<Packet> &packets) { parser.parsePackets(packets); }
zywhlc-f1lt
src/net/datastreamreader.cpp
C++
gpl3
4,209
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef PACKETPARSER_H #define PACKETPARSER_H #include <QByteArray> #include <QObject> #include <QList> #include "../core/eventdata.h" class PacketParser; class PacketBuffer; struct DataUpdates { bool commentaryUpdate; bool weatherUpdate; bool speedRecordsUpdate; bool fastestLapsUpdate; bool pitStopsUpdate; QSet<int> driverIds; DataUpdates(bool set = false) { if (set) setAllTrue(); else setAllFalse(); } void setAllTrue() { commentaryUpdate = true; weatherUpdate = true; speedRecordsUpdate = true; fastestLapsUpdate = true; pitStopsUpdate = true; driverIds.clear(); } void setAllFalse() { commentaryUpdate = false; weatherUpdate = false; speedRecordsUpdate = false; fastestLapsUpdate = false; pitStopsUpdate = false; driverIds.clear(); } }; struct Packet { int length; int type; int carID; int data; bool encrypted; QByteArray longData; }; class PacketDecrypter { public: PacketDecrypter() : salt(0x55555555), key(0) { } void resetDecryption() { salt = 0x55555555; } void decrypt(QByteArray &buf) { for (int i = 0; i < buf.size(); ++i) { salt = ((salt >> 1) ^ (salt & 0x01 ? key : 0)); unsigned char c = buf[i]; c ^= (salt & 0xff); buf[i] = c; } } bool checkDecryption(QString stream); friend class PacketParser; private: unsigned int salt; unsigned int key; }; class PacketParser : public QObject { Q_OBJECT public: PacketParser(QObject *parent = 0); void parseStreamBlock(const QByteArray &streamData); bool parsePacket(const QByteArray&, Packet &packet, int &pos); void parseKeyFrame(const QByteArray &data); void parseCarPacket(Packet &packet, bool emitSignal = true); void parseSystemPacket(Packet &packet, bool emitSignal = true); void handleRaceEvent(const Packet &packet); void handleQualiEvent(const Packet &packet); void handlePracticeEvent(const Packet &packet); bool isParsing() { return parsing; } void append(const QByteArray &buf) { streamData.append(buf); } void clearEncryptedPackets() { encryptedPackets.clear(); } void clearData() { decrypter.key = 0; eventData.clear(); } void clearBuffer(); public slots: void parsePackets(const QVector<Packet> &); void parseBufferedPackets(const QVector< QPair<Packet, qint64> > &); void parseBufferedPackets(const QPair<Packet, qint64> &); void decryptionKeyObtained(unsigned int key); void keyFrameObtained(const QByteArray &buf); void streamBlockObtained(const QByteArray &buf); void setDelay(int prevDelay, int delay); signals: void packetParsed(const Packet&); void packetParsed(const QPair<Packet, qint64>&); void eventDataChanged(const DataUpdates &dataUpdates); void driverDataChanged(int id, const DataUpdates &dataUpdates); void dataChanged(const DataUpdates &dataUpdates); void noLiveSession(bool, QString); void sessionStarted(); void requestKeyFrame(unsigned int); void requestDecryptionKey(unsigned int); private: bool parsing; int packetNo; QByteArray streamData; QList<Packet> encryptedPackets; PacketDecrypter decrypter; EventData &eventData; void savePacket(const QByteArray &buf); bool noSession; PacketBuffer *packetBuffer; DataUpdates dataUpdates; }; #endif // PACKETPARSER_H
zywhlc-f1lt
src/net/packetparser.h
C++
gpl3
5,223
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "networksettings.h" NetworkSettings::NetworkSettings() { httpHost = "http://live-timing.formula1.com"; httpLoginUrl = "http://formula1.com/reg/login/"; httpKeyFrameUrl = "http://live-timing.formula1.com/keyframe"; httpDecryptionKeyUrl = "http://live-timing.formula1.com/reg/getkey/"; socketHost = "live-timing.formula1.com"; socketPort = 4321; // socketHost = "192.168.1.2"; // socketPort = 6666; ltDataUrl = "http://lt.f1lt.pl/"; ltDataList = "http://lt.f1lt.pl/lis.php"; versionUrl = "http://f1lt.pl/version"; } void NetworkSettings::loadSettings(const QSettings &settings) { user = settings.value("login/email").toString(); passwd = settings.value("login/passwd").toString(); QString proxyHost = settings.value("proxy/host").toString(); int proxyPort = settings.value("proxy/port", 0).toInt(); int proxyType = settings.value("proxy/type", 0).toInt(); QString proxyUser = settings.value("proxy/user").toString(); QString proxyPasswd = encodePasswd(settings.value("proxy/passwd").toString()); proxyOn = settings.value("proxy/enabled", false).toBool(); proxy.setHostName(proxyHost); proxy.setPort(proxyPort); proxy.setType(QNetworkProxy::ProxyType(proxyType)); proxy.setUser(proxyUser); proxy.setPassword(proxyPasswd); } void NetworkSettings::saveSettings(QSettings &settings) { settings.setValue("login/email", user); settings.setValue("login/passwd", passwd); settings.setValue("proxy/host", proxy.hostName()); settings.setValue("proxy/port", proxy.port()); settings.setValue("proxy/type", (int)proxy.type()); settings.setValue("proxy/user", proxy.user()); settings.setValue("proxy/passwd", encodePasswd(proxy.password())); settings.setValue("proxy/enabled", proxyOn); }
zywhlc-f1lt
src/net/networksettings.cpp
C++
gpl3
3,359
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "drivertrackerwidget.h" #include "ui_drivertrackerwidget.h" #include <QKeyEvent> DriverTrackerWidget::DriverTrackerWidget(QWidget *parent) : QWidget(parent), ui(new Ui::DriverTrackerWidget), speed(1) { ui->setupUi(this); timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(update())); connect(ui->driverTracker, SIGNAL(driverExcluded(int,bool)), ui->driverRadar, SLOT(excludeDriver(int,bool))); connect(ui->driverTracker, SIGNAL(driverSelected(int)), ui->driverRadar, SLOT(selectDriver(int))); connect(ui->driverRadar, SIGNAL(driverSelected(int)), ui->driverTracker, SLOT(selectDriver(int))); } DriverTrackerWidget::~DriverTrackerWidget() { delete ui; } void DriverTrackerWidget::update() { ui->driverRadar->update(); ui->driverTracker->update(); } void DriverTrackerWidget::setup() { ui->driverRadar->loadDriversList(); ui->driverTracker->loadDriversList(); ui->driverRadar->setupDrivers(speed); ui->driverTracker->setupDrivers(speed); } void DriverTrackerWidget::loadSettings(QSettings *settings) { ui->splitter->restoreState(settings->value("ui/tracker_splitter_pos").toByteArray()); restoreGeometry(settings->value("ui/driver_tracker_geometry").toByteArray()); ui->driverTracker->setDrawDriverClassification(settings->value("ui/draw_tracker_classification").toBool()); } void DriverTrackerWidget::saveSettings(QSettings *settings) { settings->setValue("ui/tracker_splitter_pos", ui->splitter->saveState()); settings->setValue("ui/driver_tracker_geometry", saveGeometry()); settings->setValue("ui/draw_tracker_classification", ui->driverTracker->drawDriverClassification()); } void DriverTrackerWidget::on_pushButton_clicked() { close(); } void DriverTrackerWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) close(); } void DriverTrackerWidget::exec() { setWindowTitle("Driver tracker: " + EventData::getInstance().getEventInfo().eventName); ui->driverTracker->checkSetupCorrect(speed); ui->driverRadar->checkSetupCorrect(speed); show(); } void DriverTrackerWidget::drawTrackerClassification(bool val) { ui->driverTracker->setDrawDriverClassification(val); } void DriverTrackerWidget::startTimer(int s) { if (timer->isActive()) setTimerInterval(s); else { ui->driverTracker->checkSetupCorrect(speed); ui->driverRadar->checkSetupCorrect(speed); interval = s / speed; timer->start(interval); } }
zywhlc-f1lt
src/tools/drivertrackerwidget.cpp
C++
gpl3
4,092
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "sessionanalysiswidget.h" #include <QClipboard> #include <QDebug> #include <QKeyEvent> #include <QPainter> #include <QPixmap> #include <QTableWidgetItem> #include "../core/colorsmanager.h" #include "../main_gui/ltitemdelegate.h" SessionAnalysisWidget::SessionAnalysisWidget(QWidget *parent) : QWidget(parent) { ui.setupUi(this); for (int i = 0; i < ui.gridLayout->columnCount(); i += 2) { QLabel *lab = (QLabel*)ui.gridLayout->itemAtPosition(0, i)->widget(); QCheckBox *box = (QCheckBox*)ui.gridLayout->itemAtPosition(0, i+1)->widget(); box->setChecked(true); driverLabels.append(lab); driverCheckBoxes.append(box); lab = (QLabel*)ui.gridLayout->itemAtPosition(1, i)->widget(); box = (QCheckBox*)ui.gridLayout->itemAtPosition(1, i+1)->widget(); box->setChecked(true); driverLabels.append(lab); driverCheckBoxes.append(box); } setupTables(); ui.lapTimeTableWidget->setItemDelegate(new LTItemDelegate); ui.lapTimeTableWidgetFP->setItemDelegate(new LTItemDelegate); ui.lapTimeTableWidgetQuali->setItemDelegate(new LTItemDelegate); ui.lapTimeTableWidgetQ1->setItemDelegate(new LTItemDelegate); ui.lapTimeTableWidgetQ2->setItemDelegate(new LTItemDelegate); ui.lapTimeTableWidgetQ3->setItemDelegate(new LTItemDelegate); setupColors(); ui.sessionLapTimesChartQ1->setQualiPeriod(1); ui.sessionLapTimesChartQ2->setQualiPeriod(2); ui.sessionLapTimesChartQ3->setQualiPeriod(3); selected = true; // ui.splitter->refresh(); // QList<int> sizes; // sizes << 100 << 400; // ui.splitter->setSizes(sizes); // ui.lapTimeTableWidget->setGeometry(ui.lapTimeTableWidget->x(), ui.lapTimeTableWidget->y(), sizes[0], ui.lapTimeTableWidget->height()); // ui.sessionLapTimesChart->setGeometry(ui.sessionLapTimesChart->x(), ui.sessionLapTimesChart->y(), 500, ui.sessionLapTimesChart->height()); connect(ui.sessionLapTimesChart, SIGNAL(zoomChanged(int,int,double,double)), this, SLOT(onZoomChanged(int,int,double,double))); connect(ui.sessionLapTimesChartFP, SIGNAL(zoomChanged(int,int,double,double)), this, SLOT(onZoomChanged(int,int,double,double))); connect(ui.sessionLapTimesChartQuali, SIGNAL(zoomChanged(int,int,double,double)), this, SLOT(onZoomChanged(int,int,double,double))); connect(ui.sessionLapTimesChartQ1, SIGNAL(zoomChanged(int,int,double,double)), this, SLOT(onZoomChanged(int,int,double,double))); connect(ui.sessionLapTimesChartQ2, SIGNAL(zoomChanged(int,int,double,double)), this, SLOT(onZoomChanged(int,int,double,double))); connect(ui.sessionLapTimesChartQ3, SIGNAL(zoomChanged(int,int,double,double)), this, SLOT(onZoomChanged(int,int,double,double))); top10only = false; first = 0; last = 99; min = -1; max = -1; } SessionAnalysisWidget::~SessionAnalysisWidget() { } void SessionAnalysisWidget::resetView() { lapDataArray.clear(); setWindowTitle("Session analysis: " + EventData::getInstance().getEventInfo().eventName); setupBoxes(); switch(EventData::getInstance().getEventType()) { case LTPackets::RACE_EVENT: ui.raceTabWidget->setVisible(true); ui.fpTabWidget->setVisible(false); ui.qualiTabWidget->setVisible(false); break; case LTPackets::PRACTICE_EVENT: ui.raceTabWidget->setVisible(false); ui.fpTabWidget->setVisible(true); ui.qualiTabWidget->setVisible(false); break; case LTPackets::QUALI_EVENT: ui.raceTabWidget->setVisible(false); ui.fpTabWidget->setVisible(false); ui.qualiTabWidget->setVisible(true); break; default: ui.raceTabWidget->setVisible(true); ui.fpTabWidget->setVisible(false); ui.qualiTabWidget->setVisible(false); break; } ui.sessionLapTimesChart->resetZoom(); ui.sessionPositionsChart->resetZoom(); ui.sessionGapsChart->resetZoom(); ui.sessionLapTimesChartFP->resetZoom(); first = 0; last = 99; min = -1; max = -1; update(); } void SessionAnalysisWidget::resizeTables() { int w = ui.lapTimeTableWidget->width()-20;//sizes[0]-20; ui.lapTimeTableWidget->setColumnWidth(0, 0.15*w); ui.lapTimeTableWidget->setColumnWidth(1, 0.35*w); ui.lapTimeTableWidget->setColumnWidth(2, 0.2*w); ui.lapTimeTableWidget->setColumnWidth(3, 0.2*w); ui.lapTimeTableWidget->setColumnWidth(4, 0.1*w); w = ui.lapTimeTableWidgetFP->width()-20;//sizes[0]-20; ui.lapTimeTableWidgetFP->setColumnWidth(0, 0.15*w); ui.lapTimeTableWidgetFP->setColumnWidth(1, 0.32*w); ui.lapTimeTableWidgetFP->setColumnWidth(2, 0.18*w); ui.lapTimeTableWidgetFP->setColumnWidth(3, 0.17*w); ui.lapTimeTableWidgetFP->setColumnWidth(4, 0.18*w); w = ui.lapTimeTableWidgetQuali->width()-20;//sizes[0]-20; ui.lapTimeTableWidgetQuali->setColumnWidth(0, 0.1*w); ui.lapTimeTableWidgetQuali->setColumnWidth(1, 0.3*w); ui.lapTimeTableWidgetQuali->setColumnWidth(2, 0.17*w); ui.lapTimeTableWidgetQuali->setColumnWidth(3, 0.16*w); ui.lapTimeTableWidgetQuali->setColumnWidth(4, 0.17*w); ui.lapTimeTableWidgetQuali->setColumnWidth(5, 0.1*w); w = ui.lapTimeTableWidgetQ1->width()-20;//sizes[0]-20; ui.lapTimeTableWidgetQ1->setColumnWidth(0, 0.15*w); ui.lapTimeTableWidgetQ1->setColumnWidth(1, 0.32*w); ui.lapTimeTableWidgetQ1->setColumnWidth(2, 0.18*w); ui.lapTimeTableWidgetQ1->setColumnWidth(3, 0.17*w); ui.lapTimeTableWidgetQ1->setColumnWidth(4, 0.18*w); w = ui.lapTimeTableWidgetQ2->width()-20;//sizes[0]-20; ui.lapTimeTableWidgetQ2->setColumnWidth(0, 0.15*w); ui.lapTimeTableWidgetQ2->setColumnWidth(1, 0.32*w); ui.lapTimeTableWidgetQ2->setColumnWidth(2, 0.18*w); ui.lapTimeTableWidgetQ2->setColumnWidth(3, 0.17*w); ui.lapTimeTableWidgetQ2->setColumnWidth(4, 0.18*w); w = ui.lapTimeTableWidgetQ3->width()-20;//sizes[0]-20; ui.lapTimeTableWidgetQ3->setColumnWidth(0, 0.15*w); ui.lapTimeTableWidgetQ3->setColumnWidth(1, 0.32*w); ui.lapTimeTableWidgetQ3->setColumnWidth(2, 0.18*w); ui.lapTimeTableWidgetQ3->setColumnWidth(3, 0.17*w); ui.lapTimeTableWidgetQ3->setColumnWidth(4, 0.18*w); } void SessionAnalysisWidget::setupTables() { if (ui.lapTimeTableWidget->rowCount() == 0) ui.lapTimeTableWidget->insertRow(0); // QList<int> sizes = ui.splitter->sizes(); ColorsManager &sd = ColorsManager::getInstance(); setItem(ui.lapTimeTableWidget, 0, 0, "P", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidget, 0, 1, "Driver", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignLeft | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidget, 0, 2, "Time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidget, 0, 3, "Gap", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidget, 0, 4, "Lap", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); ui.lapTimeTableWidget->setRowHeight(0, 22); if (ui.lapTimeTableWidgetFP->rowCount() == 0) ui.lapTimeTableWidgetFP->insertRow(0); setItem(ui.lapTimeTableWidgetFP, 0, 0, "P", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetFP, 0, 1, "Driver", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignLeft | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetFP, 0, 2, "Time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetFP, 0, 3, "Gap", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetFP, 0, 4, "S. time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); ui.lapTimeTableWidgetQuali->setRowHeight(0, 22); if (ui.lapTimeTableWidgetQuali->rowCount() == 0) ui.lapTimeTableWidgetQuali->insertRow(0); setItem(ui.lapTimeTableWidgetQuali, 0, 0, "P", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQuali, 0, 1, "Driver", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignLeft | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQuali, 0, 2, "Time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQuali, 0, 3, "Gap", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQuali, 0, 4, "S. time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQuali, 0, 5, "Period", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); ui.lapTimeTableWidgetQuali->setRowHeight(0, 22); if (ui.lapTimeTableWidgetQ1->rowCount() == 0) ui.lapTimeTableWidgetQ1->insertRow(0); setItem(ui.lapTimeTableWidgetQ1, 0, 0, "P", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ1, 0, 1, "Driver", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignLeft | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ1, 0, 2, "Time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ1, 0, 3, "Gap", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ1, 0, 4, "S. time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); ui.lapTimeTableWidgetQ1->setRowHeight(0, 22); if (ui.lapTimeTableWidgetQ2->rowCount() == 0) ui.lapTimeTableWidgetQ2->insertRow(0); setItem(ui.lapTimeTableWidgetQ2, 0, 0, "P", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ2, 0, 1, "Driver", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignLeft | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ2, 0, 2, "Time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ2, 0, 3, "Gap", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ2, 0, 4, "S. time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); ui.lapTimeTableWidgetQ2->setRowHeight(0, 22); if (ui.lapTimeTableWidgetQ3->rowCount() == 0) ui.lapTimeTableWidgetQ3->insertRow(0); setItem(ui.lapTimeTableWidgetQ3, 0, 0, "P", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ3, 0, 1, "Driver", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignLeft | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ3, 0, 2, "Time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ3, 0, 3, "Gap", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); setItem(ui.lapTimeTableWidgetQ3, 0, 4, "S. time", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::DEFAULT)); ui.lapTimeTableWidgetQ3->setRowHeight(0, 22); resizeTables(); } void SessionAnalysisWidget::setupColors() { for (int i = 0; i < ui.gridLayout->columnCount(); i += 2) { QLabel *lab = (QLabel*)ui.gridLayout->itemAtPosition(0, i)->widget(); QPalette palette = lab->palette(); palette.setColor(QPalette::Window, ColorsManager::getInstance().getDriverColors()[i]); lab->setPalette(palette); lab = (QLabel*)ui.gridLayout->itemAtPosition(1, i)->widget(); palette = lab->palette(); palette.setColor(QPalette::Window, ColorsManager::getInstance().getDriverColors()[i+1]); lab->setPalette(palette); } setupIcons(ColorsManager::getInstance().getDriverColors()); update(); } void SessionAnalysisWidget::setupIcons(const QList<QColor> &colors) { driverIcons.clear(); for (int i = 0; i < colors.size(); ++i) { QPixmap pix(10, 22); QPainter p; p.begin(&pix); p.setPen(colors[i]); p.setBrush(colors[i]); p.drawRect(0, 0, 10, 22); p.end(); driverIcons.append(QPair<int, QIcon>(i+1, QIcon(pix))); } } void SessionAnalysisWidget::exec() { setWindowTitle("Session analysis: " + EventData::getInstance().getEventInfo().eventName); setupBoxes(); switch(EventData::getInstance().getEventType()) { case LTPackets::RACE_EVENT: ui.raceTabWidget->setVisible(true); ui.fpTabWidget->setVisible(false); ui.qualiTabWidget->setVisible(false); break; case LTPackets::PRACTICE_EVENT: ui.raceTabWidget->setVisible(false); ui.fpTabWidget->setVisible(true); ui.qualiTabWidget->setVisible(false); break; case LTPackets::QUALI_EVENT: ui.raceTabWidget->setVisible(false); ui.fpTabWidget->setVisible(false); ui.qualiTabWidget->setVisible(true); break; default: ui.raceTabWidget->setVisible(true); ui.fpTabWidget->setVisible(false); ui.qualiTabWidget->setVisible(false); break; } update(); show(); } void SessionAnalysisWidget::setupBoxes() { QStringList driverList = SeasonData::getInstance().getDriversListShort(); for (int i = 0; i < driverCheckBoxes.size() && i < driverList.size(); ++i) { QString str = driverList[i]; int idx = str.indexOf(" "); if (idx != 0) driverIcons[i].first = str.left(idx).toInt(); driverCheckBoxes[i]->setVisible(true); driverLabels[i]->setVisible(true); driverCheckBoxes[i]->setText(driverList[i]); } for (int i = driverList.size(); i < driverCheckBoxes.size(); ++i) { driverLabels[i]->setVisible(false); driverCheckBoxes[i]->setVisible(false); } } void SessionAnalysisWidget::selectDriversClicked() { selected = !selected; for (int i = 0; i < driverCheckBoxes.size(); ++i) driverCheckBoxes[i]->setChecked(selected); top10only = false; ui.top10pushButton->setChecked(top10only); update(); } void SessionAnalysisWidget::on_buttonBox_clicked(QAbstractButton *) { close(); } QTableWidgetItem* SessionAnalysisWidget::setItem(QTableWidget *table, int row, int col, QString text, Qt::ItemFlags flags, int align, QColor textColor, QBrush background) { QTableWidgetItem *item = table->item(row, col); if (!item) { item = new QTableWidgetItem(text); item->setFlags(flags); table->setItem(row, col, item); } item->setTextAlignment(align); item->setBackground(background); item->setText(text); item->setTextColor(textColor); return item; } void SessionAnalysisWidget::gatherData() { // lapDataArray.clear(); int lapsIn = 0; for (int i = 0; i < EventData::getInstance().getDriversData().size(); ++i) { DriverData &dd = EventData::getInstance().getDriversData()[i]; if (driverChecked(dd.getNumber())) { for (int j = 0; j < dd.getLapData().size(); ++j) { if (lapsIn >= lapDataArray.size()) lapDataArray.append(dd.getLapData()[j]); else lapDataArray[lapsIn] = dd.getLapData()[j]; ++lapsIn; } } } for (int i = lapDataArray.size()-1; i >= lapsIn; --i) lapDataArray.removeAt(i); qSort(lapDataArray); } bool SessionAnalysisWidget::lapInWindow(int j) { bool inTimeWindow = true; if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT) inTimeWindow = lapDataArray[j].getLapNumber() >= first && lapDataArray[j].getLapNumber() <= last; else if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT) { int minute = SeasonData::getInstance().getSessionDefaults().getFPLength() - SeasonData::getInstance().getSessionDefaults().timeToMins(lapDataArray[j].getPracticeLapExtraData().getSessionTime()); inTimeWindow = minute >= first && minute <= last; } else if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) { int qPeriod = ui.qualiTabWidget->currentIndex(); if (qPeriod == 0) { int minute = SeasonData::getInstance().getSessionDefaults().getQualiLength(lapDataArray[j].getQualiLapExtraData().getQualiPeriod()) - SeasonData::getInstance().getSessionDefaults().timeToMins(lapDataArray[j].getQualiLapExtraData().getSessionTime()); for (int k = 0; k < lapDataArray[j].getQualiLapExtraData().getQualiPeriod()-1; ++k) minute += SeasonData::getInstance().getSessionDefaults().getQualiLength(k+1); inTimeWindow = (minute >= first && minute <= last); } else { int sessLength = SeasonData::getInstance().getSessionDefaults().getQualiLength(qPeriod); int minute = sessLength - SeasonData::getInstance().getSessionDefaults().timeToMins(lapDataArray[j].getQualiLapExtraData().getSessionTime()); inTimeWindow = (minute >= first && minute <= last) && lapDataArray[j].getQualiLapExtraData().getQualiPeriod() == qPeriod; } } if (inTimeWindow)// && { if (((lapDataArray[j].getTime().isValid() && lapDataArray[j].getTime().toDouble() >= min) || min == -1) && ((lapDataArray[j].getTime().isValid() && lapDataArray[j].getTime().toDouble() <= max) || max == -1)) return true; if ((EventData::getInstance().getEventType() == LTPackets::RACE_EVENT) && (!lapDataArray[j].getTime().isValid() && min != -1 && max != -1)) { DriverData &dd = EventData::getInstance().getDriversData()[lapDataArray[j].getCarID()-1]; LapData ld = dd.getLapData(lapDataArray[j].getLapNumber()-1); if (ld.getCarID() == dd.getCarID()) { if (ld.getTime().isValid() && ld.getTime().toDouble() <= max && ld.getTime().toDouble() >= min) return true; } ld = dd.getLapData(lapDataArray[j].getLapNumber()+1); if (ld.getCarID() == dd.getCarID()) { if (ld.getTime().isValid() && ld.getTime().toDouble() <= max && ld.getTime().toDouble() >= min) return true; } } } return false; } void SessionAnalysisWidget::update(bool repaintCharts) { gatherData(); int rows = 0; QTableWidget *table = ui.lapTimeTableWidget; if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT) table = ui.lapTimeTableWidgetFP; if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) { switch (ui.qualiTabWidget->currentIndex()) { case 0: table = ui.lapTimeTableWidgetQuali; break; case 1: table = ui.lapTimeTableWidgetQ1; break; case 2: table = ui.lapTimeTableWidgetQ2; break; case 3: table = ui.lapTimeTableWidgetQ3; break; } } int firstPlace = 0; for (int i = 0; i < lapDataArray.size(); ++i) { if (lapInWindow(i)) { if (rows == 0) firstPlace = i; if (rows + 1 >= table->rowCount()) { table->insertRow(rows+1); table->setRowHeight(rows+1, 22); } if (lapDataArray[i].getCarID() < 0) continue; ColorsManager &sd = ColorsManager::getInstance(); setItem(table, rows+1, 0, QString::number(rows+1)+".", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::CYAN)); QString s = EventData::getInstance().getDriversData()[lapDataArray[i].getCarID()-1].getDriverName(); QTableWidgetItem *item = setItem(table, rows+1, 1, s, Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignLeft | Qt::AlignVCenter, sd.getColor(LTPackets::WHITE)); item->setIcon(getDriverIcon(EventData::getInstance().getDriversData()[lapDataArray[i].getCarID()-1].getNumber())); setItem(table, rows+1, 2, lapDataArray[i].getTime().toString(), Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignCenter, sd.getColor(LTPackets::WHITE)); s = (rows == 0 || !lapDataArray[i].getTime().isValid()) ? "" : "+" + DriverData::calculateGap(lapDataArray[i].getTime(), lapDataArray[firstPlace].getTime()); setItem(table, rows+1, 3, s, Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::YELLOW)); s = QString::number(lapDataArray[i].getLapNumber()); if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT) s = SeasonData::getInstance().getSessionDefaults().correctFPTime(lapDataArray[i].getPracticeLapExtraData().getSessionTime()).toString("h:mm:ss");//lapDataArray[i].sessionTime.toString("h:mm:ss") + " (" + QString::number(LTPackets::currentEventFPLength()-LTPackets::timeToMins(lapDataArray[i].sessionTime))+")"; else if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) s = SeasonData::getInstance().getSessionDefaults().correctQualiTime(lapDataArray[i].getQualiLapExtraData().getSessionTime(), lapDataArray[i].getQualiLapExtraData().getQualiPeriod()).toString("mm:ss"); setItem(table, rows+1, 4, s, Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::WHITE)); if (ui.qualiTabWidget->currentIndex() == 0) setItem(table, rows+1, 5, QString::number(lapDataArray[i].getQualiLapExtraData().getQualiPeriod()), Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::WHITE)); ++rows; } } if (rows < table->rowCount()-1) { for (int i = table->rowCount()-1; i > rows; --i) table->removeRow(i); } if (repaintCharts) { if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT) { ui.sessionLapTimesChart->setData(lapDataArray); ui.sessionLapTimesChart->update(); ui.sessionPositionsChart->setData(lapDataArray); ui.sessionPositionsChart->update(); ui.sessionGapsChart->setData(lapDataArray); ui.sessionGapsChart->update(); } if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT) { ui.sessionLapTimesChartFP->setData(lapDataArray); ui.sessionLapTimesChartFP->update(); } if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) { switch (ui.qualiTabWidget->currentIndex()) { case 0: ui.sessionLapTimesChartQuali->setData(lapDataArray); ui.sessionLapTimesChartQuali->update(); break; case 1: ui.sessionLapTimesChartQ1->setData(lapDataArray); ui.sessionLapTimesChartQ1->update(); break; case 2: ui.sessionLapTimesChartQ2->setData(lapDataArray); ui.sessionLapTimesChartQ2->update(); break; case 3: ui.sessionLapTimesChartQ3->setData(lapDataArray); ui.sessionLapTimesChartQ3->update(); break; } } } } void SessionAnalysisWidget::on_pushButton_2_clicked() { // for (int i = ui.lapTimeTableWidget->rowCount(); i > 0; --i) // ui.lapTimeTableWidget->removeRow(i); top10only = false; ui.top10pushButton->setChecked(top10only); // lapDataArray.clear(); update(); } bool SessionAnalysisWidget::driverChecked(int no) { for (int i = 0; i < driverCheckBoxes.size(); ++i) { QString str = driverCheckBoxes[i]->text(); int drvNo = -1; int idx = str.indexOf(" "); if (idx != 0) drvNo = str.left(idx).toInt(); if (drvNo == no)//LTPackets::getDriverShortName(driver) == driverCheckBoxes[i]->text()) { if (driverCheckBoxes[i]->isChecked()) return true; return false; } } return false; } void SessionAnalysisWidget::setDriverChecked(int no, bool checked) { for (int i = 0; i < driverCheckBoxes.size(); ++i) { QString str = driverCheckBoxes[i]->text(); int drvNo = -1; int idx = str.indexOf(" "); if (idx != 0) drvNo = str.left(idx).toInt(); if (drvNo == no)//LTPackets::getDriverShortName(driver) == driverCheckBoxes[i]->text()) { driverCheckBoxes[i]->setChecked(checked); } } } QIcon SessionAnalysisWidget::getDriverIcon(int no) { for (int i = 0; i < driverIcons.size(); ++i) { if (driverIcons[i].first == no) return driverIcons[i].second; } return QIcon(); } void SessionAnalysisWidget::resizeEvent(QResizeEvent *e) { resizeTables(); QWidget::resizeEvent(e); } void SessionAnalysisWidget::keyPressEvent(QKeyEvent *k) { if (k->key() == Qt::Key_Escape) close(); if (k->key() == Qt::Key_C && k->modifiers() == Qt::ControlModifier) { QTableWidget *table = ui.lapTimeTableWidget; if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT) table = ui.lapTimeTableWidgetFP; if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) { switch (ui.qualiTabWidget->currentIndex()) { case 0: table = ui.lapTimeTableWidgetQuali; break; case 1: table = ui.lapTimeTableWidgetQ1; break; case 2: table = ui.lapTimeTableWidgetQ2; break; case 3: table = ui.lapTimeTableWidgetQ3; break; } } QItemSelectionModel * selection = table->selectionModel(); QModelIndexList indexes = selection->selectedIndexes(); if(indexes.size() < 1) return; // QModelIndex::operator < sorts first by row, then by column. // this is what we need qSort(indexes.begin(), indexes.end()); // You need a pair of indexes to find the row changes QModelIndex previous = indexes.first(); indexes.removeFirst(); QString selected_text; QModelIndex current; Q_FOREACH(current, indexes) { QVariant data = table->model()->data(previous); QString text = data.toString(); selected_text.append(text); if (current.row() != previous.row()) { selected_text.append(QLatin1Char('\n')); } else { selected_text.append(QLatin1Char('\t')); } previous = current; } selected_text.append(table->model()->data(current).toString()); selected_text.append(QLatin1Char('\n')); qApp->clipboard()->setText(selected_text); } QWidget::keyPressEvent(k); } void SessionAnalysisWidget::on_top10pushButton_clicked() { top10only = !top10only; ui.top10pushButton->setChecked(top10only); if (top10only) { for (int k = 0; k < EventData::getInstance().getDriversData().size(); ++k) { if (EventData::getInstance().getDriversData()[k].getPosition() <= 10) setDriverChecked(EventData::getInstance().getDriversData()[k].getNumber(), true); else setDriverChecked(EventData::getInstance().getDriversData()[k].getNumber(), false); } } else { for (int i = 0; i < driverCheckBoxes.size(); ++i) driverCheckBoxes[i]->setChecked(true); } update(); } void SessionAnalysisWidget::onZoomChanged(int first, int last, double min,double max) { this->first = first; this->last = last; this->min = min; this->max = max; update(); } void SessionAnalysisWidget::saveSettings(QSettings &settings) { settings.setValue("ui/session_analysis_geometry", saveGeometry()); settings.setValue("ui/session_analysis_splitter", ui.splitter->saveState()); settings.setValue("ui/session_analysis_tab", ui.raceTabWidget->currentIndex()); settings.setValue("ui/session_analysis_quali_tab", ui.qualiTabWidget->currentIndex()); settings.setValue("ui/session_analysis_splitter_fp", ui.splitterFP->saveState()); settings.setValue("ui/session_analysis_splitter_quali", ui.splitterQuali->saveState()); settings.setValue("ui/session_analysis_splitter_q1", ui.splitterQ1->saveState()); settings.setValue("ui/session_analysis_splitter_q2", ui.splitterQ2->saveState()); settings.setValue("ui/session_analysis_splitter_q3", ui.splitterQ3->saveState()); settings.setValue("ui/session_analysis_race_laptime", ui.lapTimeTableWidget->width()); settings.setValue("ui/session_analysis_fp_laptime", ui.lapTimeTableWidgetFP->width()); settings.setValue("ui/session_analysis_quali_laptime", ui.lapTimeTableWidgetQuali->width()); settings.setValue("ui/session_analysis_q1_laptime", ui.lapTimeTableWidgetQ1->width()); settings.setValue("ui/session_analysis_q2_laptime", ui.lapTimeTableWidgetQ2->width()); settings.setValue("ui/session_analysis_q3_laptime", ui.lapTimeTableWidgetQ3->width()); } void SessionAnalysisWidget::loadSettings(QSettings &settings) { restoreGeometry(settings.value("ui/session_analysis_geometry").toByteArray()); ui.splitter->restoreState(settings.value("ui/session_analysis_splitter").toByteArray()); ui.raceTabWidget->setCurrentIndex(settings.value("ui/session_analysis_tab").toInt()); ui.qualiTabWidget->setCurrentIndex(settings.value("ui/session_analysis_quali_tab").toInt()); ui.splitterFP->restoreState(settings.value("ui/session_analysis_splitter_fp").toByteArray()); ui.splitterQuali->restoreState(settings.value("ui/session_analysis_splitter_quali").toByteArray()); ui.splitterQ1->restoreState(settings.value("ui/session_analysis_splitter_q1").toByteArray()); ui.splitterQ2->restoreState(settings.value("ui/session_analysis_splitter_q2").toByteArray()); ui.splitterQ3->restoreState(settings.value("ui/session_analysis_splitter_q3").toByteArray()); int w = settings.value("ui/session_analysis_race_laptime").toInt(); ui.lapTimeTableWidget->setGeometry(ui.lapTimeTableWidget->x(), ui.lapTimeTableWidget->y(), w == 0 ? 300 : w,ui.lapTimeTableWidget->height()); w = settings.value("ui/session_analysis_fp_laptime").toInt(); ui.lapTimeTableWidgetFP->setGeometry(ui.lapTimeTableWidgetFP->x(), ui.lapTimeTableWidgetFP->y(), w == 0 ? 300 : w,ui.lapTimeTableWidgetFP->height()); w = settings.value("ui/session_analysis_quali_laptime").toInt(); ui.lapTimeTableWidgetQuali->setGeometry(ui.lapTimeTableWidgetQuali->x(), ui.lapTimeTableWidgetQuali->y(), w == 0 ? 300 : w,ui.lapTimeTableWidgetQuali->height()); w = settings.value("ui/session_analysis_q1_laptime").toInt(); ui.lapTimeTableWidgetQ1->setGeometry(ui.lapTimeTableWidgetQ1->x(), ui.lapTimeTableWidgetQ1->y(), w == 0 ? 300 : w,ui.lapTimeTableWidgetQ1->height()); w = settings.value("ui/session_analysis_q2_laptime").toInt(); ui.lapTimeTableWidgetQ2->setGeometry(ui.lapTimeTableWidgetQ2->x(), ui.lapTimeTableWidgetQ2->y(), w == 0 ? 300 : w,ui.lapTimeTableWidgetQ2->height()); w = settings.value("ui/session_analysis_q3_laptime").toInt(); ui.lapTimeTableWidgetQ3->setGeometry(ui.lapTimeTableWidgetQ3->x(), ui.lapTimeTableWidgetQ3->y(), w == 0 ? 300 : w,ui.lapTimeTableWidgetQ3->height()); setupTables(); setupColors(); } void SessionAnalysisWidget::onSplitterMoved(int, int) { resizeTables(); } void SessionAnalysisWidget::on_qualiTabWidget_currentChanged(int index) { QualiLapTimesChart *chart = ui.sessionLapTimesChartQuali; if (index == 1) chart = ui.sessionLapTimesChartQ1; else if (index == 2) chart = ui.sessionLapTimesChartQ2; else if (index == 3) chart = ui.sessionLapTimesChartQ3; first = chart->getFirst(); last = chart->getLast(); min = chart->getMin(); max = chart->getMax(); update(); }
zywhlc-f1lt
src/tools/sessionanalysiswidget.cpp
C++
gpl3
35,179
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "drivertrackerinfo.h" #include "../core/eventdata.h" #include <QPainter> #include "../core/colorsmanager.h" DriverTrackerInfo::DriverTrackerInfo(QWidget *parent) : QWidget(parent) { labelBig = QPixmap(":/ui_icons/label-big.png"); labelInfoLong = QPixmap(":/ui_icons/label-info-long.png"); } void DriverTrackerInfo::setup() { ImagesFactory::getInstance().getCarThumbnailsFactory().loadCarThumbnails(240, true); QSize size = QSize(labelBig.width(), labelBig.height() + 3*labelInfoLong.height() + 6); setMinimumSize(size); } void DriverTrackerInfo::paintEvent(QPaintEvent *) { if (driverData != 0) { QPainter p; p.begin(this); paintDriverInfo(&p); paintLapsInfo(&p); paintGapsInfo(&p); p.end(); } } void DriverTrackerInfo::paintDriverInfo(QPainter *p) { int x = (width() - labelBig.width())/2; QPixmap car = ImagesFactory::getInstance().getCarThumbnailsFactory().getCarThumbnail(driverData->getNumber(), 240); int carX = x + (labelBig.width() - car.width())/2 - 2; int carY = (71 - car.height())/2; QColor color = ColorsManager::getInstance().getCarColor(driverData->getNumber()); int numX = x + 105; int numY = 70; p->setBrush(color); p->drawRect(numX, numY, 30, 20); p->drawPixmap(x, 0, labelBig); p->drawPixmap(carX, carY, car); numX = x + 20; numY = 100; QString txt = QString::number(driverData->getPosition()); if (driverData->getPosition() < 10) txt = " " + txt; p->setFont(QFont("Arial", 20, 100)); p->setPen(QColor(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND))); if (driverData->isInPits()) p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::PIT))); p->drawText(numX, numY, txt); txt = driverData->getDriverName(); p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE))); p->setFont(QFont("Arial", 10, 100)); numX = x + 140; numY = 85; p->drawText(numX, numY, txt); numX = x + 120; numY = 105; txt = SeasonData::getInstance().getTeamName(driverData->getNumber()); p->drawText(numX, numY, txt); p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::BACKGROUND))); txt = QString::number(driverData->getNumber()); if (driverData->getNumber() < 10) txt = " " + txt; numX = x + 115; numY = 85; p->drawText(numX, numY, txt); numX = x + 63; numY = 74; QPixmap helmet = ImagesFactory::getInstance().getHelmetsFactory().getHelmet(driverData->getNumber(), 30); p->drawPixmap(numX, numY, helmet); } void DriverTrackerInfo::paintLapsInfo(QPainter *p) { int x = (width() - labelBig.width())/2; int y = labelBig.height() + 2; p->drawPixmap(x, y, labelInfoLong); int nX = x + 20; int nY = y + 15; p->setFont(QFont("Arial", 10, 100)); p->setPen(QColor(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND))); //===== Current lap label======= QString txt = "Current lap:"; p->drawText(nX, nY, txt); nX = x + 115; LapData lap = driverData->getLastLap(); // if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) // lap = driverData->getSessionRecords().getBestQualiLap(EventData::getInstance().getQualiPeriod()); //===== Current lap time======= p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE))); if (EventData::getInstance().getEventType() != LTPackets::RACE_EVENT && !driverData->getLapData().isEmpty()) txt = driverData->getLapData().last().getTime().toString(); else txt = lap.getTime().toString(); p->drawText(nX, nY, txt); //===== Current sector 1 time======= p->setPen(ColorsManager::getInstance().getDefaultColor(driverData->getColorData().sectorColor(1))); nX += 65; txt = lap.getSectorTime(1).toString(); p->drawText(nX, nY, txt); //===== Current sector 2 time======= p->setPen(ColorsManager::getInstance().getDefaultColor(driverData->getColorData().sectorColor(2))); nX += 35; txt = lap.getSectorTime(2).toString(); p->drawText(nX, nY, txt); //===== Current sector 3 time======= p->setPen(ColorsManager::getInstance().getDefaultColor(driverData->getColorData().sectorColor(3))); nX += 35; txt = lap.getSectorTime(3).toString(); p->drawText(nX, nY, txt); y = labelBig.height() + labelInfoLong.height() + 4; p->drawPixmap(x, y, labelInfoLong); nX = x + 20; nY = y + 15; p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::BACKGROUND))); txt = "Best lap:"; p->drawText(nX, nY, txt); //===== Best lap time======= lap = driverData->getSessionRecords().getBestLap(); txt = lap.getTime().toString(); p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN))); nX = x + 115; p->drawText(nX, nY, txt); //===== Best sector 1 time======= p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE))); if (driverData->getSessionRecords().getBestSector(1).second == lap.getLapNumber()) p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN))); nX += 65; txt = lap.getSectorTime(1).toString(); p->drawText(nX, nY, txt); //===== Best sector 2 time======= p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE))); if (driverData->getSessionRecords().getBestSector(2).second == lap.getLapNumber()) p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN))); nX += 35; txt = lap.getSectorTime(2).toString(); p->drawText(nX, nY, txt); //===== Best sector 3 time======= p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE))); if (driverData->getSessionRecords().getBestSector(3).second == lap.getLapNumber()) p->setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN))); nX += 35; txt = lap.getSectorTime(3).toString(); p->drawText(nX, nY, txt); } void DriverTrackerInfo::paintGapsInfo(QPainter *p) { int x = (width() - labelBig.width())/2; int y = labelBig.height() + 2 * labelInfoLong.height() + 6; p->drawPixmap(x, y, labelInfoLong); int nX = x + 20; int nY = y + 15; p->setFont(QFont("Arial", 10, 100)); p->setPen(QColor(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND))); int prevPos = driverData->getPosition() - 1; int nextPos = driverData->getPosition() + 1; QColor prevColor = ColorsManager::getInstance().getDefaultColor(LTPackets::RED); QColor nextColor = ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN); if (prevPos == 0) { prevPos = 2; nextPos = 3; prevColor = ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN); } if (nextPos > EventData::getInstance().getDriversData().size()) { nextPos = driverData->getPosition() - 1; prevPos = driverData->getPosition() - 2; nextColor = ColorsManager::getInstance().getDefaultColor(LTPackets::RED); } p->drawText(nX, nY, QString("Gaps:")); // y += labelInfoShort.height() + 2; // p->drawPixmap(x, y, labelInfoShort); // p->setPen(QColor(SeasonData::getInstance().getColor(LTPackets::BACKGROUND))); // nX = x + 20; // p->drawText(nX, y+15, QString("Gap to P%1").arg(nextPos)); QString prevGap, nextGap; DriverData *prevDrv = EventData::getInstance().getDriverDataByPosPtr(prevPos); DriverData *nextDrv = EventData::getInstance().getDriverDataByPosPtr(nextPos); if (prevDrv != 0 && nextDrv != 0) { if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT) { prevGap = EventData::getInstance().calculateInterval(*driverData, *prevDrv, -1); nextGap = EventData::getInstance().calculateInterval(*driverData, *nextDrv, -1); } else if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT) { prevGap = DriverData::calculateGap(driverData->getSessionRecords().getBestLap().getTime(), prevDrv->getSessionRecords().getBestLap().getTime()); nextGap = DriverData::calculateGap(driverData->getSessionRecords().getBestLap().getTime(), nextDrv->getSessionRecords().getBestLap().getTime()); if (driverData->getPosition() != 1) prevGap = "+" + prevGap; if (driverData->getPosition() == EventData::getInstance().getDriversData().size()) nextGap = "+" + nextGap; } else { int qPeriod = EventData::getInstance().getQualiPeriod(); prevGap = DriverData::calculateGap(driverData->getSessionRecords().getBestQualiLap(qPeriod).getTime(), prevDrv->getSessionRecords().getBestQualiLap(qPeriod).getTime()); nextGap = DriverData::calculateGap(driverData->getSessionRecords().getBestQualiLap(qPeriod).getTime(), nextDrv->getSessionRecords().getBestQualiLap(qPeriod).getTime()); if (driverData->getPosition() != 1) prevGap = "+" + prevGap; if (driverData->getPosition() == EventData::getInstance().getDriversData().size()) nextGap = "+" + nextGap; } p->setPen(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE)); nX = x + 115; p->drawText(nX, nY, QString("P%1:").arg(prevPos)); p->setPen(prevColor); nX += 32; p->drawText(nX, nY, prevGap); p->setPen(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE)); nX += 55; p->drawText(nX, nY, QString("P%1:").arg(nextPos)); p->setPen(nextColor); nX += 32; p->drawText(nX, nY, nextGap); } }
zywhlc-f1lt
src/tools/drivertrackerinfo.cpp
C++
gpl3
11,458
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef DRIVERTRACKERINFO_H #define DRIVERTRACKERINFO_H #include <QWidget> #include "../core/driverdata.h" class DriverTrackerInfo : public QWidget { Q_OBJECT public: explicit DriverTrackerInfo(QWidget *parent = 0); void setDriverData(DriverData *dd) { driverData = dd; ImagesFactory::getInstance().getCarThumbnailsFactory().loadCarThumbnails(240, false); repaint(); } void setup(); void paintDriverInfo(QPainter *p); void paintLapsInfo(QPainter *p); void paintGapsInfo(QPainter *p); protected: void paintEvent(QPaintEvent *); signals: public slots: private: QPixmap labelBig; QPixmap labelInfoLong; DriverData *driverData; }; #endif // DRIVERTRACKERINFO_H
zywhlc-f1lt
src/tools/drivertrackerinfo.h
C++
gpl3
2,301
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "drivertracker.h" #include "drivertrackerpositioner.h" #include <QMouseEvent> #include "../core/colorsmanager.h" #include "../main_gui/models/qualimodel.h" DriverTracker::DriverTracker(QWidget *parent) : DriverRadar(parent), drawClassification(true) { loadDriversList(); label = QPixmap(":/ui_icons/label.png"); selectedLabel = QPixmap(":/ui_icons/label-sel.png"); } void DriverTracker::setMinimumSize() { trackMap = EventData::getInstance().getEventInfo().trackImg; QSize size = trackMap.size(); int classificationWidth = drawClassification ? label.width() : 0; size.setWidth(size.width() + classificationWidth + 10); size.setHeight(size.height() + 120);// > EventData::getInstance().getDriversData().size() * 20 + 20 ? size.height() : EventData::getInstance().getDriversData().size() * 20 + 20); QWidget::setMinimumSize(size); } void DriverTracker::setupDrivers(int speed) { if (selectedDriver != -2) selectedDriver = -1; excludedDrivers.clear(); setMinimumSize(); for (int i = 0; i < drp.size(); ++i) { drp[i]->setStartupPosition(); drp[i]->setExcluded(false); } for (int i = 0; i < drp.size(); ++i) { DriverTrackerPositioner *dtp = static_cast<DriverTrackerPositioner*>(drp[i]); int labWidth = drawClassification ? label.width() + 10 : 10; int px = labWidth + (width() - labWidth - trackMap.width())/2; int py = (height() - trackMap.height()-50)/2; int pitX = 15; int pitY = height()-60; int pitW = width() - 30; int pitH = 50; dtp->setMapCoords(px, py, pitX, pitY, pitW, pitH); dtp->setSpeed(speed); } repaint(); } void DriverTracker::loadDriversList() { dti = 0; for (int i = 0; i < drp.size(); ++i) delete drp[i]; drp.resize(EventData::getInstance().getDriversData().size()); for (int i = 0; i < drp.size(); ++i) { drp[i] = new DriverTrackerPositioner(&EventData::getInstance().getDriversData()[i]); } } void DriverTracker::resizeEvent(QResizeEvent *) { for (int i = 0; i < drp.size(); ++i) { DriverTrackerPositioner *dtp = static_cast<DriverTrackerPositioner*>(drp[i]); int labWidth = drawClassification ? label.width() + 10 : 10; int px = labWidth + (width() - labWidth - trackMap.width())/2; int py = (height() - trackMap.height()-50)/2; int pitX = 15; int pitY = height()-60; int pitW = width() - 30; int pitH = 50; dtp->setMapCoords(px, py, pitX, pitY, pitW, pitH); } } void DriverTracker::paintEvent(QPaintEvent *) { QPainter p; p.begin(this); p.setRenderHint(QPainter::Antialiasing); p.setBrush(QBrush(QColor(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND)))); p.drawRect(0, 0, width(), height()); int labWidth = drawClassification ? label.width() + 10 : 10; int px = labWidth + (width() - labWidth - trackMap.width())/2; int py = (height() - trackMap.height()-50)/2; QPoint point(px, py); p.drawPixmap(point, trackMap); p.setPen(QColor(255, 0, 0)); p.drawRect(15, height()-60, width()-30, 50); int sel = -1; for (int i = drp.size() - 1; i >= 0; --i) { if (drp[i]->getDriverId() != selectedDriver) drp[i]->paint(&p); else sel = i; } if (sel >= 0) drp[sel]->paint(&p, true); if (drawClassification) paintClassification(p); p.end(); } void DriverTracker::paintClassification(QPainter &p) { QList<DriverData *> drivers; for (int i = 0; i < EventData::getInstance().getDriversData().size(); ++i) { drivers.append(&EventData::getInstance().getDriversData()[i]); } qSort(drivers.begin(), drivers.end(), QualiLessThan(0, EventData::getInstance().getSessionRecords().getQualiBestTime(1).calc107p())); for (int i = 0; i < drivers.size(); ++i) { DriverData *dd = drivers[i];//EventData::getInstance().getDriverDataByPosPtr(i+1); if (dd != 0) { QString number = QString::number(dd->getNumber()); if (dd->getNumber() < 10) number = " " + number; QString txt = SeasonData::getInstance().getDriverShortName(dd->getDriverName()); p.setFont(QFont("Arial", 10, 100)); QColor drvColor = ColorsManager::getInstance().getCarColor(dd->getNumber()); p.setBrush(drvColor); if (isExcluded(dd->getCarID())) p.setBrush(QColor(80, 80, 80)); int x = 5; int y = 10 + i * 20; int numX = x + 35; int numY = y + p.fontMetrics().height()/2 + 8; p.setPen(QColor(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND))); p.drawRect(x, y, 70, 20); if (dd->getCarID() == selectedDriver) p.drawPixmap(x, y, selectedLabel); else p.drawPixmap(x, y, label); p.drawText(numX, numY, number); p.setPen(ColorsManager::getInstance().getDefaultColor(LTPackets::WHITE)); if (isExcluded(dd->getCarID())) p.setPen(QColor(80, 80, 80)); p.drawText(x+60, numY, txt); // if (!dd->isRetired()) { p.setPen(QColor(0,0,0)); if (dd->isInPits()) p.setPen(ColorsManager::getInstance().getDefaultColor(LTPackets::PIT)); QString pos = QString::number(i+1); if (!dd->isRetired()) { if (i+1 < 10) pos = " " + pos; p.drawText(x+10, numY, pos); } QString gap = ""; if (i > 0) { if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT) { DriverData *first = EventData::getInstance().getDriverDataByPosPtr(1); if (first) { int quali = EventData::getInstance().getQualiPeriod(); gap = DriverData::calculateGap(dd->getQualiTime(quali), first->getQualiTime(quali)); if (gap != "") gap = "+" + gap; } } else { gap = dd->getLastLap().getGap(); if (gap != "") gap = "+" + gap; if (!gap.contains("L") && gap.size() < 5) gap = " " + gap; } } else { if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT) { int laps = EventData::getInstance().getCompletedLaps() + 1; if (laps > EventData::getInstance().getEventInfo().laps) laps = EventData::getInstance().getEventInfo().laps; gap = QString("LAP %1").arg(laps); } else if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT) gap = dd->getLastLap().getTime().toString(); else gap = dd->getQualiTime(EventData::getInstance().getQualiPeriod()).toString(); } p.setPen(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::YELLOW))); if (isExcluded(dd->getCarID())) p.setPen(QColor(80, 80, 80)); p.drawText(x+105, numY, gap); } } } } void DriverTracker::mousePressEvent(QMouseEvent *event) { if (event->buttons() == Qt::LeftButton && event->pos().x() >= 5 && event->pos().x() <= 5 + label.width() && event->pos().y() >= 10 && event->pos().y() <= 10 + 20 * EventData::getInstance().getDriversData().size()) { int pos = (event->pos().y() - 10) / 20 + 1; DriverData *dd = EventData::getInstance().getDriverDataByPosPtr(pos); if (dd != 0 && !isExcluded(dd->getCarID())) { if (dd->getCarID() == selectedDriver) selectedDriver = -1; else selectedDriver = dd->getCarID(); } emit driverSelected(selectedDriver); } else { bool found = false; for (int i = 0; i < drp.size(); ++i) { if (drp[i]->isSelected(event->pos())) { if (selectedDriver != drp[i]->getDriverId()) selectedDriver = drp[i]->getDriverId(); else selectedDriver = -1; found = true; break; } } if (!found) selectedDriver = -1; emit driverSelected(selectedDriver); } repaint(); } void DriverTracker::mouseDoubleClickEvent(QMouseEvent *event) { if (event->buttons() == Qt::LeftButton && event->pos().x() >= 5 && event->pos().x() <= 5 + label.width() && event->pos().y() >= 10 && event->pos().y() <= 10 + 20 * EventData::getInstance().getDriversData().size()) { int pos = (event->pos().y() - 10) / 20 + 1; DriverData *dd = EventData::getInstance().getDriverDataByPosPtr(pos); if (dd != 0) { if (dd->getCarID() == selectedDriver) selectedDriver = -1; bool found = false; for (int i = 0; i < excludedDrivers.size(); ++i) { if (dd->getCarID() == excludedDrivers[i]) { excludedDrivers.takeAt(i); excludeDriver(dd->getCarID(), false); emit driverExcluded(dd->getCarID(), false); found = true; break; } } if (!found) { excludedDrivers.append(dd->getCarID()); emit driverExcluded(dd->getCarID(), true); excludeDriver(dd->getCarID(), true); } } } repaint(); } bool DriverTracker::isExcluded(int id) { for (int i = 0; i < excludedDrivers.size(); ++i) { if (excludedDrivers[i] == id) return true; } return false; }
zywhlc-f1lt
src/tools/drivertracker.cpp
C++
gpl3
12,132
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef FOLLOWADRIVERDIALOG_H #define FOLLOWADRIVERDIALOG_H #include <QDialog> #include <QList> #include <QTableWidgetItem> #include "../core/colorsmanager.h" #include "../core/eventdata.h" #include "../net/packetparser.h" namespace Ui { class FollowADriverDialog; } class FollowADriverDialog : public QDialog { Q_OBJECT public: explicit FollowADriverDialog(QWidget *parent = 0); ~FollowADriverDialog(); int getNumber(); void setFont(const QFont &); void printDriverInfo(const DriverData &dd); void printDataTable(const DriverData &dd, const QList<DriverData*> &drivers); void printLapTimesTable(const DriverData &dd, const QList<DriverData*> &drivers); QList<DriverData*> getDriversArray(int pos); void loadDriversList(); // void loadCarImages(); void setupTables(); void setCurrentDriver(int id); void clearData(bool clearDriverList = true); void clearRow(int row); bool driverInRange(const DriverData &dd); void updateButtonsState(const DriverData &dd); public slots: void show(int currentDriverId = 0); int exec(int currentDriverId = 0); void comboBoxValueChanged(int); void updateData(); void driverUpdated(const DriverData &dd) { if (driverInRange(dd)) updateData(); } void updateData(const DataUpdates &dataUpdates) { QSetIterator<int> iter(dataUpdates.driverIds); while (iter.hasNext()) { DriverData *dd = eventData.getDriverDataByIdPtr(iter.next()); if ((dd != 0) && driverInRange(*dd)) updateData(); } } protected: void resizeEvent(QResizeEvent *); void keyPressEvent(QKeyEvent *); private slots: void on_leftButton_clicked(); void on_rightButton_clicked(); void on_dataTableWidget_cellDoubleClicked(int row, int column); private: QTableWidgetItem* setItem(QTableWidget *table, int row, int col, QString text = "", Qt::ItemFlags flags = Qt::NoItemFlags, int align = Qt::AlignCenter, QColor textColor = ColorsManager::getInstance().getColor(LTPackets::DEFAULT), QBrush background = QBrush()); Ui::FollowADriverDialog *ui; QList<QPixmap> *smallCarImg; EventData &eventData; int thumbnailsSize; }; #endif // FOLLOWADRIVERDIALOG_H
zywhlc-f1lt
src/tools/followadriverdialog.h
C++
gpl3
3,870
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "drivertrackerpositioner.h" #include "../core/colorsmanager.h" #include "../core/eventdata.h" DriverTrackerPositioner::DriverTrackerPositioner(DriverData *dd) : DriverRadarPositioner(dd), coordinatesCount(0), mapX(0), mapY(0) { } void DriverTrackerPositioner::setStartupPosition() { int laps = EventData::getInstance().getEventInfo().laps; lapped = false; qualiOut = false; inPits = false; finished = false; coordinatesCount = SeasonData::getInstance().getTrackMapsCoordinates().getCurrentTrackCoordinates().coordinates.size();//EventData::getInstance().getEventInfo().trackCoordinates.coordinates.size(); //a very rough estimate ;) avgTime = 200 - 30 * log10(laps*laps); if (EventData::getInstance().getSessionRecords().getFastestLap().getTime().isValid()) avgTime = EventData::getInstance().getSessionRecords().getFastestLap().getTime().toDouble(); //if it's raining, we add 10 seconds if (EventData::getInstance().getWeather().getWetDry().getValue() == 1) avgTime += 10; //if SC is on track, we add 1 minute if (EventData::getInstance().getFlagStatus() == LTPackets::SAFETY_CAR_DEPLOYED) avgTime += 60; if (driverData && (driverData->isInPits() || driverData->isRetired())) { inPits = true; calculatePitPosition(); } else if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT && (!EventData::getInstance().isSessionStarted() || !driverData->getLastLap().getSectorTime(1).isValid())) { inPits = false; currentDeg = coordinatesCount-(round((double)driverData->getPosition()/3))-1; currentLapTime = -(avgTime-(avgTime * currentDeg) / coordinatesCount); } else { currentLapTime = 0; for (int i = 0; i < 3; ++i) currentLapTime += driverData->getLastLap().getSectorTime(i+1).toDouble(); calculatePosition(); } } void DriverTrackerPositioner::calculatePosition() { EventData &ev = EventData::getInstance(); if (!ev.isSessionStarted()) return; TrackCoordinates trackCoordinates = SeasonData::getInstance().getTrackMapsCoordinates().getCurrentTrackCoordinates(); if (/*driverData->getLastLap().getTime().toString() != "OUT" &&*/ currentDeg > 0) { if (driverData->getLastLap().getSectorTime(1).isValid() && ((ev.getEventType() == LTPackets::RACE_EVENT && driverData->getColorData().lapTimeColor() == LTPackets::YELLOW) || (!driverData->getLastLap().getSectorTime(2).isValid() || !driverData->getLastLap().getSectorTime(3).isValid())) && currSector == 1) { currSector = 2; currentDeg = trackCoordinates.indexes[0]; } else if (driverData->getLastLap().getSectorTime(2).isValid() && !driverData->getLastLap().getSectorTime(3).isValid() && currSector == 2 && driverData->getLastLap().getTime().toString() != "OUT") { currSector = 3; currentDeg = trackCoordinates.indexes[1]; } else { currentDeg += ((double)coordinatesCount / avgTime) / speed; //(360 * currentLapTime) / avgTime; } } else { currentDeg += ((double)coordinatesCount / avgTime) / speed; } if ((int)(round(currentDeg)) >= coordinatesCount) currentDeg = 0; } void DriverTrackerPositioner::calculatePitOutPosition() { currentDeg = SeasonData::getInstance().getTrackMapsCoordinates().getCurrentTrackCoordinates().indexes[2]; } void DriverTrackerPositioner::calculatePitPosition() { EventData &ev = EventData::getInstance(); if (ev.getEventType() == LTPackets::QUALI_EVENT && ((ev.getQualiPeriod() == 2 && driverData->getPosition() > 17) || (ev.getQualiPeriod() == 3 && driverData->getPosition() > 10))) qualiOut = true; } bool DriverTrackerPositioner::isSelected(QPoint p) { QPoint coord = getCoordinates(); if ((abs(p.x() - coord.x())) <= 13 && ((coord.y() - p.y() <= 13) && (p.y() - coord.y() <= 26))) return true; return false; } QPoint DriverTrackerPositioner::getCoordinates() { if (inPits) { int no = driverData->getNumber() - 1; if (no > 12) no -= 1; int x = pitX + no * pitW / EventData::getInstance().getDriversData().size() + 13; int y = pitY + pitH/3; return QPoint(x, y); } if (coordinatesCount == 0) return QPoint(0, 0); // if ((int)round(currentDeg) >= 0 && (int)round(currentDeg) < coordinatesCount) { int idx = (int)round(currentDeg); if (idx == coordinatesCount) idx = coordinatesCount - 1; double x = mapX + SeasonData::getInstance().getTrackMapsCoordinates().getCurrentTrackCoordinates().coordinates[idx].x(); double y = mapY + SeasonData::getInstance().getTrackMapsCoordinates().getCurrentTrackCoordinates().coordinates[idx].y(); return QPoint(x, y); } } QPoint DriverTrackerPositioner::getSCCoordinates() { // if (inPits) // { // int no = driverData->getNumber() - 1; // if (no > 12) // no -= 1; // int x = pitX + no * pitW / EventData::getInstance().getDriversData().size() + 13; // int y = pitY + pitH/2; // return QPoint(x, y); // } if (coordinatesCount == 0) return QPoint(0, 0); // if ((int)round(currentDeg) >= 0 && (int)round(currentDeg) < coordinatesCount) { int idx = (int)round(currentDeg + 3 * ((double)coordinatesCount / avgTime) / speed) % coordinatesCount; if (!driverData->getLapData().isEmpty() && !driverData->getLapData().last().getRaceLapExtraData().isSCLap()) idx = 0; double x = mapX + SeasonData::getInstance().getTrackMapsCoordinates().getCurrentTrackCoordinates().coordinates[idx].x(); double y = mapY + SeasonData::getInstance().getTrackMapsCoordinates().getCurrentTrackCoordinates().coordinates[idx].y(); return QPoint(x, y); } } void DriverTrackerPositioner::paint(QPainter *p, bool selected) { if (driverData && driverData->getCarID() > 0) { QPoint point = getCoordinates(); QColor drvColor = ColorsManager::getInstance().getCarColor(driverData->getNumber()); p->setBrush(QBrush(drvColor)); QPen pen(drvColor); if (driverData->getPosition() == 1) { pen.setColor(ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN)); pen.setWidth(3); } if (driverData->isRetired() || qualiOut) { pen.setColor(QColor(255, 0, 0)); pen.setWidth(3); } if (selected) { pen.setColor(ColorsManager::getInstance().getDefaultColor(LTPackets::YELLOW)); pen.setWidth(3); } p->setPen(pen); p->setFont(QFont("Arial", 8, 75)); if (!excluded) { QPixmap helmet = ImagesFactory::getInstance().getHelmetsFactory().getHelmet(driverData->getNumber(), 24); p->drawPixmap(point.x()-12, point.y()-12, helmet); QString number = SeasonData::getInstance().getDriverShortName(driverData->getDriverName());//QString::number(driverData->getNumber()); p->setBrush(drvColor); p->drawRoundedRect(point.x()-12, point.y()+15, helmet.width(), 14, 4, 4); p->setPen(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND)); int numX = point.x() - 18 + p->fontMetrics().width(number)/2; int numY = point.y() + 20 + p->fontMetrics().height()/2; p->drawText(numX, numY, number); } if (driverData->getPosition() == 1 && EventData::getInstance().getFlagStatus() == LTPackets::SAFETY_CAR_DEPLOYED) { point = getSCCoordinates(); p->setPen(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND)); p->setBrush(QColor(ColorsManager::getInstance().getDefaultColor(LTPackets::YELLOW))); p->drawEllipse(point, 15, 15); p->setFont(QFont("Arial", 12, 100)); QString number = "SC"; int numX = point.x() - p->fontMetrics().width(number)/2; int numY = point.y() + 14 - p->fontMetrics().height()/2; p->drawText(numX, numY, number); } } }
zywhlc-f1lt
src/tools/drivertrackerpositioner.cpp
C++
gpl3
9,984
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef TRACKRECORDSDIALOG_H #define TRACKRECORDSDIALOG_H #include <QDialog> #include <QModelIndex> #include <QSettings> #include "driverrecordsdialog.h" namespace Ui { class TrackRecordsDialog; } class TrackRecordsDialog : public QDialog { Q_OBJECT public: explicit TrackRecordsDialog(QWidget *parent = 0); ~TrackRecordsDialog(); void loadTrackRecords(int year = 0); void updateRecordsLabels(); void exec(); void saveSettings(QSettings &settings); void loadSettings(QSettings &settings); void setFont(const QFont &font); void update(); private slots: void on_listWidget_clicked(const QModelIndex &index); void on_toolButton_clicked(); void on_toolButton_2_clicked(); void on_pushButton_clicked(); void on_trackVersionBox_activated(const QString &arg1); void on_yearBox_currentIndexChanged(const QString &arg1); private: Ui::TrackRecordsDialog *ui; int currentIndex; TrackVersion *currentTV; TrackWeekendRecords *currentTWR; DriverRecordsDialog *drDialog; }; #endif // TRACKRECORDSDIALOG_H
zywhlc-f1lt
src/tools/trackrecordsdialog.h
C++
gpl3
2,645
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef DRIVERRADARPOSITIONER_H #define DRIVERRADARPOSITIONER_H #include <QPainter> #include "../core/driverdata.h" class DriverRadarPositioner { public: DriverRadarPositioner(DriverData *dd = 0, int x = 0, int y = 0, double r = 0.0, double rP = 0.0, double rL = 0.0); virtual ~DriverRadarPositioner() { } virtual void paint(QPainter *p, bool selected = false); virtual QPoint getCoordinates(); void update(); void calculateAvgs(); void setDriverData(DriverData *dd); virtual void setStartupPosition(); void setRadarCoords(int x, int y, double r, double rP, double rL) { radarX = x; radarY = y; radarR = r; radarPitR = rP; radarLappedR = rL; } virtual void calculatePosition(); virtual void calculatePitPosition(); virtual void calculatePitOutPosition() { currentDeg = 0; } virtual int maxDeg() { return 360; } void setSpeed(int s) { speed = s; } int getDriverId() { if (driverData != 0) return driverData->getCarID(); return -1; } virtual bool isSelected(QPoint p); bool isExcluded() { return excluded; } void setExcluded(bool ex) { excluded = ex; } protected: DriverData *driverData; double avgTime; double avgSectorTimes[2]; double sectorPositions[2]; int currSector; double currentDeg; int currentLapTime; bool startingNewLap; bool inPits; bool lapped; bool finished; bool qualiOut; bool excluded; bool wetTrack; int speed; private: int radarX, radarY; double radarR, radarPitR, radarLappedR; }; #endif // DRIVERRADARPOSITIONER_H
zywhlc-f1lt
src/tools/driverradarpositioner.h
C++
gpl3
3,309
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "trackrecordsdialog.h" #include "ui_trackrecordsdialog.h" #include "../core/colorsmanager.h" #include "../core/trackrecords.h" bool loadingRecords = false; TrackRecordsDialog::TrackRecordsDialog(QWidget *parent) : QDialog(parent, Qt::Window), ui(new Ui::TrackRecordsDialog), currentIndex(-1), currentTV(0), currentTWR(0) { ui->setupUi(this); drDialog = new DriverRecordsDialog(this); } TrackRecordsDialog::~TrackRecordsDialog() { delete ui; } void TrackRecordsDialog::exec() { TrackRecords &tr = TrackRecords::getInstance(); QStringList sList = tr.getTrackList(); if (ui->listWidget->count() != sList.size()) { for (int i = 0; i < sList.size(); ++i) { QListWidgetItem *item = ui->listWidget->item(i); if (!item) { item = new QListWidgetItem(); ui->listWidget->insertItem(i, item); } item->setText(sList[i]); } for (int i = ui->listWidget->count() - 1; i >= tr.getTrackRecords().size(); --i) { QListWidgetItem *item = ui->listWidget->item(i); ui->listWidget->removeItemWidget(item); } } loadTrackRecords(); QDialog::show(); } void TrackRecordsDialog::loadTrackRecords(int year) { loadingRecords = true; TrackVersion *tv = currentTV; TrackWeekendRecords *twr = currentTWR; Track *tr = 0; if (year == 0) year = EventData::getInstance().getEventInfo().fpDate.year(); if (currentIndex == -1) { currentIndex = TrackRecords::getInstance().getCurrentTrackRecords(&tr, &twr, &tv); if (twr == 0 || tv == 0 || tr == 0) { if (TrackRecords::getInstance().getTrackRecords().isEmpty()) return; tr = &TrackRecords::getInstance().getTrackRecords().first(); tv = &(*tr)[0]; twr = &(*tv)[0]; } QList<QListWidgetItem*> items = ui->listWidget->findItems(tr->name, Qt::MatchContains); if (!items.isEmpty()) { ui->listWidget->setCurrentItem(items.first()); } } else { tr = &TrackRecords::getInstance()[currentIndex]; tr->getTrackRecords(&tv, &twr, year); if (tv == 0 || twr == 0) { tv = &tr->last(); twr = &tv->last(); } } setWindowTitle("Track records: " + tr->name); ui->trackNameLabel->setText(tr->name); ui->trackMapLabel->setPixmap(tv->map); ui->trackVersionBox->clear(); for (int i = 0; i < tr->trackVersions.size(); ++i) ui->trackVersionBox->addItem(QString::number(tr->trackVersions[i].year)); int idx = ui->trackVersionBox->findText(QString::number(tv->year)); if (idx != -1) ui->trackVersionBox->setCurrentIndex(idx); else ui->trackVersionBox->setCurrentIndex(0); ui->yearBox->clear(); for (int i = 0; i < tv->trackWeekendRecords.size(); ++i) ui->yearBox->addItem(QString::number(tv->trackWeekendRecords[i].year)); idx = ui->yearBox->findText(QString::number(twr->year)); if (idx != -1) ui->yearBox->setCurrentIndex(idx); else ui->yearBox->setCurrentIndex(0); currentTV = tv; currentTWR = twr; updateRecordsLabels(); loadingRecords = false; } void TrackRecordsDialog::updateRecordsLabels() { TrackVersion *tv = currentTV; TrackWeekendRecords *twr = currentTWR; QPalette palette; ui->qRTLabel->setText(tv->trackRecords[QUALI_RECORD].time.toString()); ui->qRDLabel->setText(tv->trackRecords[QUALI_RECORD].driver); ui->qRDTLabel->setText(tv->trackRecords[QUALI_RECORD].team); ui->qRYLabel->setText(tv->trackRecords[QUALI_RECORD].year); ui->rRTLabel->setText(tv->trackRecords[RACE_RECORD].time.toString()); ui->rRDLabel->setText(tv->trackRecords[RACE_RECORD].driver); ui->rRDTLabel->setText(tv->trackRecords[RACE_RECORD].team); ui->rRYLabel->setText(tv->trackRecords[RACE_RECORD].year); ui->s1TLabel->setText(twr->sessionRecords[S1_RECORD].time.toString()); ui->s1DLabel->setText(twr->sessionRecords[S1_RECORD].driver); ui->s1DTLabel->setText(twr->sessionRecords[S1_RECORD].team); ui->s1SLabel->setText(twr->sessionRecords[S1_RECORD].session); ui->s2TLabel->setText(twr->sessionRecords[S2_RECORD].time.toString()); ui->s2DLabel->setText(twr->sessionRecords[S2_RECORD].driver); ui->s2DTLabel->setText(twr->sessionRecords[S2_RECORD].team); ui->s2SLabel->setText(twr->sessionRecords[S2_RECORD].session); ui->s3TLabel->setText(twr->sessionRecords[S3_RECORD].time.toString()); ui->s3DLabel->setText(twr->sessionRecords[S3_RECORD].driver); ui->s3DTLabel->setText(twr->sessionRecords[S3_RECORD].team); ui->s3SLabel->setText(twr->sessionRecords[S3_RECORD].session); ui->tTLabel->setText(twr->sessionRecords[TIME_RECORD].time.toString()); ui->tDLabel->setText(twr->sessionRecords[TIME_RECORD].driver); ui->tDTLabel->setText(twr->sessionRecords[TIME_RECORD].team); ui->tSLabel->setText(twr->sessionRecords[TIME_RECORD].session); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::WHITE)); ui->qRDLabel->setPalette(palette); ui->qRDTLabel->setPalette(palette); ui->rRDLabel->setPalette(palette); ui->rRDTLabel->setPalette(palette); ui->s1DLabel->setPalette(palette); ui->s1DTLabel->setPalette(palette); ui->s2DLabel->setPalette(palette); ui->s2DTLabel->setPalette(palette); ui->s3DLabel->setPalette(palette); ui->s3DTLabel->setPalette(palette); ui->tDLabel->setPalette(palette); ui->tDTLabel->setPalette(palette); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::VIOLET)); ui->qRTLabel->setPalette(palette); ui->rRTLabel->setPalette(palette); ui->s1TLabel->setPalette(palette); ui->s2TLabel->setPalette(palette); ui->s3TLabel->setPalette(palette); ui->tTLabel->setPalette(palette); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->qRYLabel->setPalette(palette); ui->rRYLabel->setPalette(palette); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::CYAN)); ui->s1SLabel->setPalette(palette); ui->s2SLabel->setPalette(palette); ui->s3SLabel->setPalette(palette); ui->tSLabel->setPalette(palette); } void TrackRecordsDialog::on_listWidget_clicked(const QModelIndex &index) { currentIndex = index.row(); currentTV = 0; currentTWR = 0; loadTrackRecords(); if (currentTWR == 0) return; if (drDialog->isVisible()) { QString name; if (currentIndex > -1) name = TrackRecords::getInstance()[currentIndex].name; drDialog->loadRecords(*currentTWR, name); } } void TrackRecordsDialog::on_toolButton_clicked() { if (currentIndex > 0) { --currentIndex; currentTV = 0; currentTWR = 0; ui->listWidget->setCurrentRow(currentIndex); loadTrackRecords(); } } void TrackRecordsDialog::on_toolButton_2_clicked() { if (currentIndex < TrackRecords::getInstance().getTrackRecords().size() - 1) { ++currentIndex; currentTV = 0; currentTWR = 0; ui->listWidget->setCurrentRow(currentIndex); loadTrackRecords(); } } void TrackRecordsDialog::saveSettings(QSettings &settings) { settings.setValue("ui/trackrecords_geometry", saveGeometry()); settings.setValue("ui/trackrecords_splitter", ui->splitter->saveState()); drDialog->saveSettings(settings); } void TrackRecordsDialog::loadSettings(QSettings &settings) { restoreGeometry(settings.value("ui/trackrecords_geometry").toByteArray()); ui->splitter->restoreState(settings.value("ui/trackrecords_splitter").toByteArray()); drDialog->loadSettings(settings); } void TrackRecordsDialog::setFont(const QFont &font) { for (int i = 0; i < ui->gridLayout_4->count(); ++i) { ui->gridLayout_4->itemAt(i)->widget()->setFont(font); } for (int i = 0; i < ui->gridLayout_2->count(); ++i) { ui->gridLayout_2->itemAt(i)->widget()->setFont(font); } ui->trackRecordsLabel->setFont(font); ui->recordsLabel->setFont(font); ui->label->setFont(font); drDialog->setFont(font); } void TrackRecordsDialog::on_pushButton_clicked() { if (currentIndex == -1 || currentTWR == 0) return; TrackRecords::getInstance().gatherSessionRecords(true); QString name = TrackRecords::getInstance()[currentIndex].name; drDialog->exec(*currentTWR, name); } void TrackRecordsDialog::update() { if (currentIndex == -1) return; Track &tr = TrackRecords::getInstance()[currentIndex]; if ((tr.name == EventData::getInstance().getEventInfo().eventPlace) && (ui->yearBox->currentText().toInt() == EventData::getInstance().getEventInfo().fpDate.year())) { TrackRecords::getInstance().gatherSessionRecords(true); updateRecordsLabels(); if (drDialog->isVisible()) { QString name = TrackRecords::getInstance()[currentIndex].name; drDialog->loadRecords(*currentTWR, name); } } } void TrackRecordsDialog::on_yearBox_currentIndexChanged(const QString &arg1) { if (!loadingRecords && currentTV != 0) { currentTWR = &currentTV->getTrackWeekendRecords(arg1.toInt()); if (*currentTWR != TrackWeekendRecords::null()) loadTrackRecords(currentTWR->year); else currentTWR = 0; } } void TrackRecordsDialog::on_trackVersionBox_activated(const QString &arg1) { if (!loadingRecords && currentIndex != -1) { currentTV = &TrackRecords::getInstance()[currentIndex].getTrackVersion(arg1.toInt()); if (*currentTV != TrackVersion::null()) { currentTWR = &(*currentTV)[0]; loadTrackRecords(currentTWR->year); } else { currentTV = 0; currentTWR = 0; } } }
zywhlc-f1lt
src/tools/trackrecordsdialog.cpp
C++
gpl3
11,749
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef HEADTOHEADDIALOG_H #define HEADTOHEADDIALOG_H #include <QDialog> #include <QList> #include "../core/seasondata.h" #include "../charts/lapcompchart.h" #include "../net/packetparser.h" #include <QComboBox> namespace Ui { class HeadToHeadDialog; } class HeadToHeadDialog : public QDialog { Q_OBJECT public: explicit HeadToHeadDialog(QWidget *parent = 0); ~HeadToHeadDialog(); void setFont(const QFont &); void loadDriversList(); int getNumber(int); void setCurrentDriver(int id); public slots: int exec(int currentDriverId = 0); void show(int currentDriverId = 0); void comboBoxValueChanged(int); void updateData(); void updateCharts(); void driverUpdated(const DriverData &dd) { for (int i = 0; i < 2; ++i) { if (dd.getCarID() == eventData.getDriverId(getNumber(i))) { updateData(); updateCharts(); return; } } } void updateData(const DataUpdates &dataUpdates) { for (int i = 0; i < 2; ++i) { if (dataUpdates.driverIds.contains(eventData.getDriverId(getNumber(i)))) { updateData(); updateCharts(); return; } } } protected: void resizeEvent(QResizeEvent *); void keyPressEvent(QKeyEvent *); private slots: void on_pushButton_clicked(); private: Ui::HeadToHeadDialog *ui; QComboBox *comboBox[2]; LapCompChart *lapCompChart; GapCompChart *gapCompChart; PosCompChart *posCompChart; QList<QPixmap> *smallCarImg; EventData &eventData; int thumbnailsSize; }; #endif // HEADTOHEADDIALOG_H
zywhlc-f1lt
src/tools/headtoheaddialog.h
C++
gpl3
3,287
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "followadriverdialog.h" #include "ui_followadriverdialog.h" #include <QClipboard> #include <QDebug> #include <QKeyEvent> #include "../core/colorsmanager.h" #include "../main_gui/ltitemdelegate.h" FollowADriverDialog::FollowADriverDialog(QWidget *parent) : QDialog(parent, Qt::Window), ui(new Ui::FollowADriverDialog), eventData(EventData::getInstance()), thumbnailsSize(180) { ui->setupUi(this); loadDriversList(); setupTables(); ui->lapTimesTableWidget->setItemDelegate(new LTItemDelegate()); ui->dataTableWidget->setItemDelegate(new LTItemDelegate()); connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(comboBoxValueChanged(int))); } FollowADriverDialog::~FollowADriverDialog() { delete ui; } void FollowADriverDialog::loadDriversList() { /*smallCarImg = */ImagesFactory::getInstance().getCarThumbnailsFactory().loadCarThumbnails(thumbnailsSize); // ui->comboBox->clear(); clearData(); if (ui->comboBox->itemText(1) == "") { QStringList list = SeasonData::getInstance().getDriversList(); if (list.size() > 1) ui->comboBox->addItems(SeasonData::getInstance().getDriversList()); } } void FollowADriverDialog::setupTables() { if (ui->dataTableWidget->rowCount() == 0) { for (int i = 0; i < 6; ++i) { ui->dataTableWidget->insertRow(i); ui->dataTableWidget->setRowHeight(i, 22); } } if (ui->lapTimesTableWidget->rowCount() == 0) { for (int i = 0; i < 6; ++i) { ui->lapTimesTableWidget->insertRow(i); ui->lapTimesTableWidget->setRowHeight(i, 22); } } setItem(ui->dataTableWidget, 0, 0, "P", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignRight | Qt::AlignVCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); setItem(ui->dataTableWidget, 0, 1, "Name", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignLeft | Qt::AlignVCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); setItem(ui->dataTableWidget, 0, 2, "Int.", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); setItem(ui->dataTableWidget, 0, 3, "Time", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); setItem(ui->dataTableWidget, 0, 4, "S1", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); setItem(ui->dataTableWidget, 0, 5, "S2", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); setItem(ui->dataTableWidget, 0, 6, "S3", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); setItem(ui->lapTimesTableWidget, 0, 0, "Lap", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); } QTableWidgetItem* FollowADriverDialog::setItem(QTableWidget *table, int row, int col, QString text, Qt::ItemFlags flags, int align, QColor textColor, QBrush background) { QTableWidgetItem *item = table->item(row, col); if (!item) { item = new QTableWidgetItem(text); item->setFlags(flags); table->setItem(row, col, item); } item->setTextAlignment(align); item->setBackground(background); item->setText(text); item->setTextColor(textColor); return item; } int FollowADriverDialog::exec(int currentDriverId) { // loadDriversData(); // if (ui->comboBox->itemText(1) == "")// && eventData.driversData[0].driver != "") // { // ui->comboBox->addItems(SeasonData::getInstance().getDriversList()); // } setCurrentDriver(currentDriverId); updateData(); return QDialog::exec(); } void FollowADriverDialog::show(int currentDriverId) { // loadDriversData(); // if (ui->comboBox->itemText(1) == "")// && eventData.driversData[0].driver != "") // { // ui->comboBox->addItems(SeasonData::getInstance().getDriversList()); // } setCurrentDriver(currentDriverId); updateData(); QDialog::show(); } void FollowADriverDialog::updateData() { int no = getNumber(); DriverData *dd = eventData.getDriverDataPtr(no); setWindowTitle("Follow a driver"); if (dd != 0 && dd->getCarID() > 0) { setWindowTitle("Follow a driver - " + dd->getDriverName()); updateButtonsState(*dd); printDriverInfo(*dd); QList<DriverData*> drivers = getDriversArray(dd->getPosition()); printDataTable(*dd, drivers); printLapTimesTable(*dd, drivers); } else clearData(false); } void FollowADriverDialog::printDriverInfo(const DriverData &dd) { ui->carImageLabel->setPixmap(ImagesFactory::getInstance().getCarThumbnailsFactory().getCarThumbnail(dd.getNumber(), thumbnailsSize)); ui->bestLapLabel->setText(dd.getSessionRecords().getBestLap().getTime().toString() + QString(" (L%1)").arg(dd.getSessionRecords().getBestLap().getLapNumber())); QPalette palette; if (eventData.getEventType() == LTPackets::RACE_EVENT) { if (dd.getPosition() > 1) ui->gapLabel->setText(dd.getLastLap().getGap()); else ui->gapLabel->setText(""); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::PIT)); ui->pitsLabel->setText(QString::number(dd.getPitStops().size())); ui->pitsLabel->setPalette(palette); ui->pitStopsLabel->setText("Pit stops:"); QPalette palette = ui->pitStopsLabel->palette(); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); ui->pitStopsLabel->setPalette(palette); } else { QString gap = ""; if (dd.getPosition() != 1) { DriverData *fd = eventData.getDriverDataByPosPtr(1); if (fd) gap = DriverData::calculateGap(dd.getLastLap().getTime(), fd->getLastLap().getTime()); } ui->gapLabel->setText(gap); ui->pitsLabel->setText(""); palette = ui->pitStopsLabel->palette(); if (dd.getColorData().numberColor() == LTPackets::PIT) { ui->pitStopsLabel->setText("In pits"); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::PIT)); } else { ui->pitStopsLabel->setText("On track"); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); } ui->pitStopsLabel->setPalette(palette); } palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::GREEN)); ui->bestLapLabel->setPalette(palette); palette.setBrush(QPalette::Foreground, ColorsManager::getInstance().getColor(LTPackets::YELLOW)); ui->gapLabel->setPalette(palette); } void FollowADriverDialog::printDataTable(const DriverData &dd, const QList<DriverData*> &drivers) { for (int i = 0; i < drivers.size(); ++i) { if (drivers[i] != 0) { QBrush bg = QBrush(); if (drivers[i]->getCarID() == dd.getCarID()) bg = QBrush(QColor(50, 50, 50)); QString interval = ""; double dInterval = 0.0; bool ok; LapData ld = drivers[i]->getLastLap(); LapData ldCurr = dd.getLastLap(); if (eventData.getEventType() != LTPackets::RACE_EVENT) { ld = drivers[i]->getSessionRecords().getBestLap(); ldCurr = dd.getSessionRecords().getBestLap(); } if (eventData.getEventType() == LTPackets::QUALI_EVENT) { if (drivers[i]->getSessionRecords().getBestQualiLap(eventData.getQualiPeriod()).getTime().isValid()) ld = drivers[i]->getSessionRecords().getBestQualiLap(eventData.getQualiPeriod()); if (dd.getSessionRecords().getBestQualiLap(eventData.getQualiPeriod()).getTime().isValid()) ldCurr = dd.getSessionRecords().getBestQualiLap(eventData.getQualiPeriod()); } QString time = ld.getTime().toString(); QColor colors[5]; colors[0] = ColorsManager::getInstance().getColor(LTPackets::VIOLET); if (drivers[i]->getCarID() != dd.getCarID()) { if (eventData.getEventType() == LTPackets::RACE_EVENT) interval = eventData.calculateInterval(dd, *drivers[i], -1);//dd.getLapData().last().getLapNumber()); else interval = DriverData::calculateGap(ld.getTime(), ldCurr.getTime()); dInterval = interval.toDouble(&ok); if (ld.getTime().isValid() && ldCurr.getTime().isValid()) { QString gap = DriverData::calculateGap(ld.getTime(), ldCurr.getTime()); colors[1] = ColorsManager::getInstance().getColor(LTPackets::GREEN); if (gap.size() > 0 && gap[0] != '-') { gap = "+" + gap; colors[1] = ColorsManager::getInstance().getColor(LTPackets::RED); } time += " ("+gap+")"; } else if (!time.contains("IN PIT") && !time.contains("OUT")) colors[1] = ColorsManager::getInstance().getColor(LTPackets::GREEN); else if (time.contains("LAP")) colors[1] = ColorsManager::getInstance().getColor(LTPackets::RED); else { time = QString("IN PIT (%1)").arg(drivers[i]->getPitTime(ld.getLapNumber())) ; colors[1] = ColorsManager::getInstance().getColor(LTPackets::RED); } for (int j = 1; j <= 3; ++j) { if ((ld.getSectorTime(j).toDouble() < ldCurr.getSectorTime(j).toDouble()) || dd.getLastLap().getSectorTime(j).toDouble() == 0.0) colors[j+1] = ColorsManager::getInstance().getColor(LTPackets::GREEN); else colors[j+1] = ColorsManager::getInstance().getColor(LTPackets::RED); if (ok && eventData.getEventType() == LTPackets::RACE_EVENT && ld.getLapNumber() == ldCurr.getLapNumber() && ldCurr.getSectorTime(3).toDouble() == 0 && ld.getSectorTime(3).toDouble() == 0 && ldCurr.getSectorTime(j).toDouble() != 0 && ld.getSectorTime(j).toDouble() != 0) { dInterval += ldCurr.getSectorTime(j).toDouble() - ld.getSectorTime(j).toDouble(); } } if (ok) { interval = QString::number(dInterval, 'f', 1); if (dInterval > 0) interval = "+" + interval; } if (interval.size() > 0 && interval[0] == '+') colors[0] = ColorsManager::getInstance().getColor(LTPackets::RED); } else { for (int j = 0; j < 5; ++j) colors[j] = ColorsManager::getInstance().getColor(LTPackets::WHITE); if (time.contains("IN PIT") || time.contains("OUT")) { colors[1] = ColorsManager::getInstance().getColor(LTPackets::RED); time = QString("IN PIT (%1)").arg(drivers[i]->getPitTime(ld.getLapNumber())) ; } } setItem(ui->dataTableWidget, i+1, 0, QString::number(drivers[i]->getPosition()), Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignRight | Qt::AlignVCenter, ColorsManager::getInstance().getColor(LTPackets::CYAN), bg); setItem(ui->dataTableWidget, i+1, 1, drivers[i]->getDriverName(), Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignLeft | Qt::AlignVCenter, ColorsManager::getInstance().getColor(LTPackets::WHITE), bg); setItem(ui->dataTableWidget, i+1, 2, interval, Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, colors[0], bg); setItem(ui->dataTableWidget, i+1, 3, time, Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, colors[1], bg); for (int j = 1; j <= 3; ++j) { setItem(ui->dataTableWidget, i+1, 3+j, ld.getSectorTime(j).toString(), Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, colors[j+1], bg); } } else clearRow(i+1); } } void FollowADriverDialog::printLapTimesTable(const DriverData &dd, const QList<DriverData*> &drivers) { // int lap = eventData.getCompletedLaps(); for (int i = 0; i < drivers.size(); ++i) { if (drivers[i] != 0) setItem(ui->lapTimesTableWidget, 0, i+1, QString("%1 %2").arg(drivers[i]->getPosition()).arg(drivers[i]->getDriverName()), Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::WHITE)); } int i, j, k; // for (i = lap, k = 0; i >= lap-5; --i, ++k) for (i = 0, k = dd.getLapData().size()-1; k >= 0 && i < 5; --k, ++i) { int lapNo = dd.getLapData()[k].getLapNumber(); setItem(ui->lapTimesTableWidget, i+1, 0, QString("%1.").arg(lapNo), Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); for (j = 0; j < drivers.size(); ++j) { if (drivers[j] == 0) continue; LapData ld = drivers[j]->getLapData(lapNo); QString time = ld.getTime().toString(); QColor color = ColorsManager::getInstance().getColor(LTPackets::WHITE); if (drivers[j]->getCarID() != dd.getCarID()) { if (ld.getTime().isValid() && dd.getLapData()[k].getTime().isValid()) { QString gap = DriverData::calculateGap(ld.getTime(), dd.getLapData()[k].getTime()); color = ColorsManager::getInstance().getColor(LTPackets::GREEN); if (gap.size() > 0 && gap[0] != '-') { color = ColorsManager::getInstance().getColor(LTPackets::RED); gap = "+" + gap; } time += " (" + gap + ")"; } else { if (time == "IN PIT" || time == "OUT") { color = ColorsManager::getInstance().getColor(LTPackets::RED); time = QString("IN PIT (%1)").arg(drivers[j]->getPitTime(ld.getLapNumber())) ; } else if (time.contains("LAP")) color = ColorsManager::getInstance().getColor(LTPackets::RED); else color = ColorsManager::getInstance().getColor(LTPackets::GREEN); } } else if (!dd.getLapData()[k].getTime().isValid()) { color = ColorsManager::getInstance().getColor(LTPackets::RED); if (time == "IN PIT" || time == "OUT") time = QString("IN PIT (%1)").arg(drivers[j]->getPitTime(ld.getLapNumber())) ; } if (ld.getCarID() == drivers[j]->getCarID()) setItem(ui->lapTimesTableWidget, i+1, j+1, time, Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, color); else setItem(ui->lapTimesTableWidget, i+1, j+1, "", Qt::ItemIsSelectable | Qt::ItemIsEnabled); } } for (; i < 5; ++i) for (j = 0; j < 6; ++j) setItem(ui->lapTimesTableWidget, i+1, j, "", Qt::ItemIsSelectable | Qt::ItemIsEnabled); } void FollowADriverDialog::clearData(bool clearDriverList) { for (int i = 0; i <= 5; ++i) { if (i > 0) clearRow(i); for (int j = 0; j < 6; ++j) { if (i > 0 || (i == 0 && j > 0)) setItem(ui->lapTimesTableWidget, i, j, "", Qt::ItemIsSelectable | Qt::ItemIsEnabled); } ui->carImageLabel->setPixmap(QPixmap()); ui->bestLapLabel->setText(""); ui->pitsLabel->setText(""); ui->gapLabel->setText(""); if (eventData.getEventType() != LTPackets::RACE_EVENT) ui->pitStopsLabel->setText(""); } if (clearDriverList) ui->comboBox->clear(); } void FollowADriverDialog::clearRow(int row) { for (int i = 0; i < 7; ++i) setItem(ui->dataTableWidget, row, i, "", Qt::ItemIsSelectable | Qt::ItemIsEnabled); } void FollowADriverDialog::comboBoxValueChanged(int) { updateData(); } void FollowADriverDialog::setFont(const QFont &font) { ui->dataFrame->setFont(font); ui->dataTableWidget->setFont(font); ui->lapTimesTableWidget->setFont(font); } bool FollowADriverDialog::driverInRange(const DriverData &dd) { int no = getNumber(); DriverData *cd = eventData.getDriverDataPtr(no); if (cd != 0) { QList<DriverData*> drivers = getDriversArray(cd->getPosition()); for (int i = 0; i < drivers.size(); ++i) { if (drivers[i] != 0 && drivers[i]->getCarID() == dd.getCarID()) return true; } } return false; } QList<DriverData*> FollowADriverDialog::getDriversArray(int pos) { int first = pos - 2; int last = pos + 2; if (first <= 0) { last = 5; first = 1; } if (last > eventData.getDriversData().size()) { last = eventData.getDriversData().size(); first = last - 4; } DriverData *cd = eventData.getDriverDataByPosPtr(pos); bool lastIsRetired = false; do { DriverData *dd = eventData.getDriverDataByPosPtr(last); if (dd != 0 && dd->isRetired() && !cd->isRetired() && first > 0) { lastIsRetired = true; --last; --first; } else lastIsRetired = false; } while(lastIsRetired); QList<DriverData*> drivers; int i, j; for (i = first, j = 0; i <= last; ++i, ++j) { drivers << eventData.getDriverDataByPosPtr(i); } return drivers; } void FollowADriverDialog::setCurrentDriver(int id) { if (id != 0) { DriverData dd = eventData.getDriverDataById(id); if (dd.getCarID() > 0) { int idx = ui->comboBox->findText(QString("%1 %2").arg(dd.getNumber()).arg(dd.getDriverName())); if (idx != -1) ui->comboBox->setCurrentIndex(idx); } } } int FollowADriverDialog::getNumber() { QString text = ui->comboBox->currentText(); int no = -1; int idx = text.indexOf(" "); if (idx != -1) { bool ok; no = text.left(idx).toInt(&ok); if (!ok) no = -1; } return no; } void FollowADriverDialog::updateButtonsState(const DriverData &dd) { if (dd.getPosition() == 1 && ui->leftButton->isEnabled()) ui->leftButton->setEnabled(false); else if (dd.getPosition() != 1 && !ui->leftButton->isEnabled()) ui->leftButton->setEnabled(true); if (dd.getPosition() == eventData.getDriversData().size() && ui->rightButton->isEnabled()) ui->rightButton->setEnabled(false); else if (dd.getPosition() < eventData.getDriversData().size() && !ui->rightButton->isEnabled()) ui->rightButton->setEnabled(true); } void FollowADriverDialog::resizeEvent(QResizeEvent *) { int w = ui->dataTableWidget->width(); ui->dataTableWidget->setColumnWidth(0, 0.06*w); ui->dataTableWidget->setColumnWidth(1, 0.25*w); ui->dataTableWidget->setColumnWidth(2, 0.1*w); ui->dataTableWidget->setColumnWidth(3, 0.29*w); ui->dataTableWidget->setColumnWidth(4, 0.1*w); ui->dataTableWidget->setColumnWidth(5, 0.1*w); ui->dataTableWidget->setColumnWidth(6, 0.1*w); w = ui->lapTimesTableWidget->width(); ui->lapTimesTableWidget->setColumnWidth(0, 0.05*w); ui->lapTimesTableWidget->setColumnWidth(1, 0.19*w); ui->lapTimesTableWidget->setColumnWidth(2, 0.19*w); ui->lapTimesTableWidget->setColumnWidth(3, 0.19*w); ui->lapTimesTableWidget->setColumnWidth(4, 0.19*w); ui->lapTimesTableWidget->setColumnWidth(5, 0.19*w); } void FollowADriverDialog::on_leftButton_clicked() { int no = getNumber(); DriverData *dd = eventData.getDriverDataPtr(no); if (dd != 0 && dd->getPosition() > 1) { DriverData *ddPtr = eventData.getDriverDataByPosPtr(dd->getPosition()-1); if (ddPtr) { setCurrentDriver(ddPtr->getCarID()); // updateButtonsState(*ddPtr); } } } void FollowADriverDialog::on_rightButton_clicked() { int no = getNumber(); DriverData *dd = eventData.getDriverDataPtr(no); if (dd->getPosition() < eventData.getDriversData().size()) { DriverData *ddPtr = eventData.getDriverDataByPosPtr(dd->getPosition()+1); if (ddPtr) { setCurrentDriver(ddPtr->getCarID()); // updateButtonsState(*ddPtr); } } } void FollowADriverDialog::on_dataTableWidget_cellDoubleClicked(int row, int) { QTableWidgetItem *item = ui->dataTableWidget->item(row, 0); if (item) { DriverData *dd = eventData.getDriverDataByPosPtr(item->text().toInt()); if (dd) { setCurrentDriver(dd->getCarID()); QList<QTableWidgetItem *> items = ui->dataTableWidget->findItems(dd->getDriverName(), Qt::MatchExactly); if (!items.isEmpty()) ui->dataTableWidget->setCurrentItem(items.first()); } } } void FollowADriverDialog::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier) { // QItemSelectionModel * selection = ui->dataTableWidget->selectionModel(); QModelIndexList indexes[2]; indexes[0] = ui->dataTableWidget->selectionModel()->selectedIndexes(); indexes[1] = ui->lapTimesTableWidget->selectionModel()->selectedIndexes(); QTableWidget *table[2]; table[0] = ui->dataTableWidget; table[1] = ui->lapTimesTableWidget; QString selected_text; for (int i = 0; i < 2; ++i) { if (indexes[i].size() < 1) continue; qSort(indexes[i].begin(), indexes[i].end()); QModelIndex previous = indexes[i].first(); indexes[i].removeFirst(); QModelIndex current; Q_FOREACH(current, indexes[i]) { QVariant data = table[i]->model()->data(previous); QString text = data.toString(); selected_text.append(text); if (current.row() != previous.row()) selected_text.append(QLatin1Char('\n')); else selected_text.append(QLatin1Char('\t')); previous = current; } selected_text.append(table[i]->model()->data(current).toString()); selected_text.append(QLatin1Char('\n')); } qApp->clipboard()->setText(selected_text); } if (event->key() == Qt::Key_Escape) close(); }
zywhlc-f1lt
src/tools/followadriverdialog.cpp
C++
gpl3
25,418
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "sessiontimeswidget.h" #include "ui_sessiontimeswidget.h" #include <QDebug> #include <QStringList> #include "../core/colorsmanager.h" #include "../core/eventdata.h" #include "../core/seasondata.h" #include "../main_gui/ltitemdelegate.h" SessionTimesWidget::SessionTimesWidget(QWidget *parent) : QWidget(parent), ui(new Ui::SessionTimesWidget), selectedDriver(0), relativeTimes(false) { ui->setupUi(this); loadDriversList(); ui->timesTableWidget->setItemDelegate(new LTItemDelegate()); ui->driversListWidget->setItemDelegate(new LTItemDelegate()); connect(ui->timesTableWidget->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(onHeaderClicked(int))); connect(ui->timesTableWidget->horizontalHeader(), SIGNAL(sectionDoubleClicked(int)), this, SLOT(onHeaderDoubleClicked(int))); } SessionTimesWidget::~SessionTimesWidget() { delete ui; } QTableWidgetItem* SessionTimesWidget::setItem(int row, int col, QString text, Qt::ItemFlags flags, int align, QColor textColor, QBrush background) { if (ui->timesTableWidget->rowCount() <= row) { ui->timesTableWidget->insertRow(row); // for (int i = 0; i < ui->timesTableWidget->columnCount(); ++i) // { // if (i != col) // ui->timesTableWidget->setItem(row, i, new QTableWidgetItem()); // } } QTableWidgetItem *item = ui->timesTableWidget->item(row, col); if (!item) { item = new QTableWidgetItem(text); item->setFlags(flags); ui->timesTableWidget->setItem(row, col, item); } item->setTextAlignment(align); item->setBackground(background); item->setText(text); item->setTextColor(textColor); return item; } void SessionTimesWidget::loadDriversList() { QStringList list = SeasonData::getInstance().getDriversList(); list.removeFirst(); ui->driversListWidget->clear(); ui->driversListWidget->addItems(list); for (int i = ui->timesTableWidget->columnCount(); i < list.size(); ++i) { ui->timesTableWidget->insertColumn(i); } if (list.size() < ui->timesTableWidget->columnCount()) { for (int i = ui->timesTableWidget->columnCount(); i >= list.size(); --i) ui->timesTableWidget->removeColumn(i); } ui->timesTableWidget->clear(); for (int i = 0; i < ui->driversListWidget->count(); ++i) { ui->driversListWidget->item(i)->setFlags(ui->driversListWidget->item(i)->flags() | Qt::ItemIsUserCheckable); QTableWidgetItem *item = ui->timesTableWidget->horizontalHeaderItem(i); if (item == 0) { item = new QTableWidgetItem(); ui->timesTableWidget->setHorizontalHeaderItem(i, item); } item->setText(getName(i)); } restoreCheckedArray(); } void SessionTimesWidget::exec() { setWindowTitle("Session times: " + EventData::getInstance().getEventInfo().eventName); loadDriversList(); update(); show(); } void SessionTimesWidget::update() { switch(EventData::getInstance().getEventType()) { case LTPackets::RACE_EVENT: handleRaceEvent(); break; case LTPackets::QUALI_EVENT: handleQualiEvent(); break; case LTPackets::PRACTICE_EVENT: handlePracticeEvent(); break; } if (ui->top10Button->isChecked()) on_top10Button_toggled(true); } void SessionTimesWidget::handleRaceEvent() { for (int i = 0; i < ui->timesTableWidget->columnCount(); ++i) { int driverNo = getNumber(i); DriverData *dd = EventData::getInstance().getDriverDataPtr(driverNo); if (dd != 0) { LapTime bestTime = dd->getSessionRecords().getBestLap().getTime(); int bestLapNo = dd->getSessionRecords().getBestLap().getLapNumber(); // for (int j = 1; j <= EventData::getInstance().getCompletedLaps(); ++j) for (int j = EventData::getInstance().getCompletedLaps(); j >= 1; --j) { LapData ld = dd->getLapData(j); QColor color = ((!relativeTimes || bestLapNo == j) && ld.getTime().isValid()) ? ColorsManager::getInstance().getColor(LTPackets::WHITE) : ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (ld.getCarID() == dd->getCarID()) { QString time = ld.getTime().toString(); if (time == "IN PIT") time = QString("IN PIT (%1)").arg(dd->getPitTime(j)); if (selectedDriver != 0 && ui->relativeButton->isChecked()) { color = (ld.getTime().isValid()) ? ColorsManager::getInstance().getColor(LTPackets::WHITE) : ColorsManager::getInstance().getColor(LTPackets::RED); if (selectedDriver != dd) { LapData sld = selectedDriver->getLapData(j); if (sld.getCarID() == selectedDriver->getCarID() && sld.getTime().isValid() && ld.getTime().isValid()) { color = (ld < sld) ? ColorsManager::getInstance().getColor(LTPackets::GREEN) : ColorsManager::getInstance().getColor(LTPackets::RED); if (relativeTimes) time = DriverData::calculateGap(ld.getTime(), sld.getTime()); } } } else { if (j == bestLapNo) color = ColorsManager::getInstance().getColor(LTPackets::GREEN); if (!ld.getTime().isValid()) color = ColorsManager::getInstance().getColor(LTPackets::RED); if (relativeTimes && bestLapNo != j && ld.getTime().isValid()) time = DriverData::calculateGap(ld.getTime(), bestTime); } setItem(EventData::getInstance().getCompletedLaps()-j, i, time, Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, color); QTableWidgetItem *item = ui->timesTableWidget->verticalHeaderItem(j-1); if (item == 0) { item = new QTableWidgetItem(); item->setTextAlignment(Qt::AlignVCenter | Qt::AlignRight); ui->timesTableWidget->setVerticalHeaderItem(j-1, item); } item->setText(QString::number(EventData::getInstance().getCompletedLaps()-j+1)); } else setItem(EventData::getInstance().getCompletedLaps()-j, i, "", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, color); } } } removeRows(EventData::getInstance().getCompletedLaps()); } void SessionTimesWidget::handleQualiEvent() { int row = 0; for (int q = 3; q >= 1; --q) { for (int i = 0; i < ui->timesTableWidget->columnCount(); ++i) setItem(row, i, QString("Q%1").arg(q), Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, ColorsManager::getInstance().getColor(LTPackets::BACKGROUND), /*SeasonData::getInstance().getColor(LTPackets::YELLOW)*/QBrush(QColor(123, 123, 123))); QTableWidgetItem *item = ui->timesTableWidget->verticalHeaderItem(row); if (item == 0) { item = new QTableWidgetItem(); ui->timesTableWidget->setVerticalHeaderItem(row, item); } item->setText(QString("Q%1").arg(q)); ++row; // for (int j = 1; j <= SeasonData::getInstance().getSessionDefaults().getQualiLength(q); ++j) for (int j = SeasonData::getInstance().getSessionDefaults().getQualiLength(q); j >= 1; --j) { bool rowInserted = false; LapData sld; if (selectedDriver != 0 && ui->relativeButton->isChecked()) sld = selectedDriver->getQLapData(j, q); for (int i = 0; i < ui->timesTableWidget->columnCount(); ++i) { int driverNo = getNumber(i); DriverData *dd = EventData::getInstance().getDriverDataPtr(driverNo); if (dd != 0) { LapTime bestTime = dd->getSessionRecords().getBestQualiLap(3).getTime(); int bestQ = 3; while (!bestTime.isValid() && bestQ > 1) { --bestQ; bestTime = dd->getSessionRecords().getBestQualiLap(bestQ).getTime(); } int bestLapNo = dd->getSessionRecords().getBestQualiLap(bestQ).getLapNumber(); LapData ld = dd->getQLapData(j, q); QColor color = ((!relativeTimes || bestLapNo == ld.getLapNumber()) && ld.getTime().isValid()) ? ColorsManager::getInstance().getColor(LTPackets::WHITE) : ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (ld.getTime().toString().contains("LAP")) color = ColorsManager::getInstance().getColor(LTPackets::RED); if (ld.getCarID() == dd->getCarID()) { QString time = ld.getTime().toString(); if (selectedDriver != 0 && ui->relativeButton->isChecked()) { color = ld.getTime().isValid() ? ColorsManager::getInstance().getColor(LTPackets::WHITE) : ColorsManager::getInstance().getColor(LTPackets::RED); if (selectedDriver != dd && sld.getCarID() == selectedDriver->getCarID() && sld.getTime().isValid() && ld.getTime().isValid()) { color = (ld < sld) ? ColorsManager::getInstance().getColor(LTPackets::GREEN) : ColorsManager::getInstance().getColor(LTPackets::RED); if (relativeTimes) time = DriverData::calculateGap(ld.getTime(), sld.getTime()); } } else { if (ld.getLapNumber() == bestLapNo) color = ColorsManager::getInstance().getColor(LTPackets::GREEN); if (relativeTimes && bestLapNo != ld.getLapNumber() && ld.getTime().isValid()) time = DriverData::calculateGap(ld.getTime(), bestTime); } setItem(row, i, time, Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, color); rowInserted = true; } else setItem(row, i, "", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter); } } if (rowInserted) { QTableWidgetItem *item = ui->timesTableWidget->verticalHeaderItem(row); if (item == 0) { item = new QTableWidgetItem(); ui->timesTableWidget->setVerticalHeaderItem(row, item); } item->setTextAlignment(Qt::AlignVCenter | Qt::AlignRight); item->setText(QString::number(j)); ++row; } } } removeRows(row); } void SessionTimesWidget::handlePracticeEvent() { int row = 0; // for (int j = 1; j <= SeasonData::getInstance().getSessionDefaults().getFPLength(); ++j) for (int j = SeasonData::getInstance().getSessionDefaults().getFPLength(); j >= 1; --j) { bool rowInserted = false; LapData sld; if (selectedDriver != 0 && ui->relativeButton->isChecked()) sld = selectedDriver->getFPLapData(j); for (int i = 0; i < ui->timesTableWidget->columnCount(); ++i) { int driverNo = getNumber(i); DriverData *dd = EventData::getInstance().getDriverDataPtr(driverNo); if (dd != 0) { LapTime bestTime = dd->getSessionRecords().getBestLap().getTime(); int bestLapNo = dd->getSessionRecords().getBestLap().getLapNumber(); LapData ld = dd->getFPLapData(j); QColor color = ((!relativeTimes || bestLapNo == ld.getLapNumber()) && ld.getTime().isValid()) ? ColorsManager::getInstance().getColor(LTPackets::WHITE) : ColorsManager::getInstance().getColor(LTPackets::YELLOW); if (ld.getTime().toString().contains("LAP")) color = ColorsManager::getInstance().getColor(LTPackets::RED); if (ld.getCarID() == dd->getCarID()) { QString time = ld.getTime().toString(); if (selectedDriver != 0 && ui->relativeButton->isChecked()) { color = ld.getTime().isValid() ? ColorsManager::getInstance().getColor(LTPackets::WHITE) : ColorsManager::getInstance().getColor(LTPackets::RED); if (selectedDriver != dd && sld.getCarID() == selectedDriver->getCarID() && sld.getTime().isValid() && ld.getTime().isValid()) { color = (ld < sld) ? ColorsManager::getInstance().getColor(LTPackets::GREEN) : ColorsManager::getInstance().getColor(LTPackets::RED); if (relativeTimes) time = DriverData::calculateGap(ld.getTime(), sld.getTime()); } } else { if (ld.getLapNumber() == bestLapNo) color = ColorsManager::getInstance().getColor(LTPackets::GREEN); if (relativeTimes && bestLapNo != ld.getLapNumber() && ld.getTime().isValid()) time = DriverData::calculateGap(ld.getTime(), bestTime); } setItem(row, i, time, Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter, color); rowInserted = true; } else setItem(row, i, "", Qt::ItemIsSelectable | Qt::ItemIsEnabled, Qt::AlignCenter); } } if (rowInserted) { QTableWidgetItem *item = ui->timesTableWidget->verticalHeaderItem(row); if (item == 0) { item = new QTableWidgetItem(); item->setTextAlignment(Qt::AlignVCenter | Qt::AlignRight); ui->timesTableWidget->setVerticalHeaderItem(row, item); } item->setText(QString::number(j)); ++row; } } removeRows(row); } int SessionTimesWidget::getNumber(int row) { QListWidgetItem *item = ui->driversListWidget->item(row); if (item) { QString text = item->text(); int no = -1; int idx = text.indexOf(" "); if (idx != -1) { bool ok; no = text.left(idx).toInt(&ok); if (!ok) no = -1; } return no; } return -1; } QString SessionTimesWidget::getName(int row) { QListWidgetItem *item = ui->driversListWidget->item(row); if (item) { QString text = item->text(); QRegExp reg("(\\d+)\\s(\\D+)"); if (reg.indexIn(text) != -1) { return SeasonData::getInstance().getDriverShortName(reg.cap(2)); } // int idx = text.indexOf(" "); // if (idx != -1) // { // return text.right(text.size()-idx-1); // } } return QString(); } void SessionTimesWidget::removeRows(int row) { for (int i = ui->timesTableWidget->rowCount()-1; i >= row; --i) ui->timesTableWidget->removeRow(i); } void SessionTimesWidget::setFont(const QFont &font) { ui->timesTableWidget->setFont(font); } void SessionTimesWidget::saveSettings(QSettings &settings) { settings.setValue("ui/session_times_geometry", saveGeometry()); settings.setValue("ui/session_times_splitter", ui->splitter->saveState()); settings.setValue("ui/session_times_table", ui->timesTableWidget->saveGeometry()); settings.setValue("ui/session_times_columns", checkedArray); QList<QVariant> columnSizes; for (int i = 0; i < ui->timesTableWidget->columnCount(); ++i) columnSizes << ui->timesTableWidget->columnWidth(i); settings.setValue("ui/session_times_column_sizes", columnSizes); } void SessionTimesWidget::loadSettings(QSettings &settings) { restoreGeometry(settings.value("ui/session_times_geometry").toByteArray()); ui->splitter->restoreState(settings.value("ui/session_times_splitter").toByteArray()); ui->timesTableWidget->restoreGeometry(settings.value("ui/session_times_table").toByteArray()); checkedArray = settings.value("ui/session_times_columns", QByteArray(ui->driversListWidget->count(), 2)).toByteArray(); QList<QVariant> columnSizes = settings.value("ui/session_times_column_sizes").toList(); for (int i = 0; i < columnSizes.size(); ++i) { if (columnSizes[i].toInt() > 0) ui->timesTableWidget->setColumnWidth(i, columnSizes[i].toInt()); } } void SessionTimesWidget::saveCheckedArray() { checkedArray.resize(ui->driversListWidget->count()); for (int i = 0; i < ui->driversListWidget->count(); ++i) { QListWidgetItem *item = ui->driversListWidget->item(i); checkedArray[i] = (int)item->checkState(); } } void SessionTimesWidget::restoreCheckedArray() { for (int i = 0; i < ui->driversListWidget->count(); ++i) { QListWidgetItem *item = ui->driversListWidget->item(i); if (i < checkedArray.size()) { int t = checkedArray[i]; item->setCheckState((Qt::CheckState)t); if ((Qt::CheckState)t == Qt::Unchecked) ui->timesTableWidget->setColumnHidden(i, true); } else item->setCheckState(Qt::Checked); } } void SessionTimesWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Escape) on_closeButton_clicked(); QWidget::keyPressEvent(event); } void SessionTimesWidget::on_closeButton_clicked() { saveCheckedArray(); close(); } void SessionTimesWidget::on_flagButton_clicked() { relativeTimes = !relativeTimes; if (relativeTimes) ui->flagButton->setText("Absolute times"); else ui->flagButton->setText("Relative times"); update(); } void SessionTimesWidget::on_driversListWidget_clicked(const QModelIndex &index) { ui->relativeButton->setEnabled(true); int row = index.row(); int no = getNumber(row); QListWidgetItem *item = ui->driversListWidget->item(row); if (item) { if (item->checkState() == Qt::Unchecked) { ui->timesTableWidget->setColumnHidden(row, true); if (ui->relativeButton->isChecked()) { ui->relativeButton->setChecked(false); update(); } } else { ui->timesTableWidget->selectColumn(row); ui->timesTableWidget->setColumnHidden(row, false); selectedDriver = EventData::getInstance().getDriverDataPtr(no); if (ui->relativeButton->isChecked()) { update(); } } } } void SessionTimesWidget::on_driversListWidget_doubleClicked(const QModelIndex &index) { ui->relativeButton->setChecked(true); on_driversListWidget_clicked(index); } void SessionTimesWidget::on_relativeButton_toggled(bool) { update(); } void SessionTimesWidget::onHeaderClicked(int col) { ui->relativeButton->setEnabled(true); ui->driversListWidget->clearSelection(); QListWidgetItem *item = ui->driversListWidget->item(col); if (item) ui->driversListWidget->setCurrentItem(item); int no = getNumber(col); selectedDriver = EventData::getInstance().getDriverDataPtr(no); if (ui->relativeButton->isChecked()) update(); } void SessionTimesWidget::onHeaderDoubleClicked(int col) { ui->relativeButton->setChecked(true); onHeaderClicked(col); } void SessionTimesWidget::on_top10Button_toggled(bool toggled) { for (int i = 0; i < ui->driversListWidget->count(); ++i) { QRegExp reg("(\\d+)\\s\\D+"); if (reg.indexIn(ui->driversListWidget->item(i)->text()) != -1) { int no = reg.cap(1).toInt(); if (toggled) { if (EventData::getInstance().getDriverDataPtr(no)->getPosition() > 10) { ui->driversListWidget->item(i)->setCheckState(Qt::Unchecked); ui->timesTableWidget->setColumnHidden(i, true); } else { ui->driversListWidget->item(i)->setCheckState(Qt::Checked); ui->timesTableWidget->setColumnHidden(i, false); } } else { ui->driversListWidget->item(i)->setCheckState(Qt::Checked); ui->timesTableWidget->setColumnHidden(i, false); } } } }
zywhlc-f1lt
src/tools/sessiontimeswidget.cpp
C++
gpl3
23,178
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "driverradarpositioner.h" #include <QDebug> #include "../core/colorsmanager.h" #include "../core/eventdata.h" DriverRadarPositioner::DriverRadarPositioner(DriverData *dd, int x, int y, double r, double r1, double rL) : driverData(dd), avgTime(100), currSector(1), currentDeg(0), currentLapTime(0), startingNewLap(false), inPits(false), lapped(false), finished(false), qualiOut(false), excluded(false), speed(1), radarX(x), radarY(y), radarR(r), radarPitR(r1), radarLappedR(rL) { avgSectorTimes[0] = 0.0; avgSectorTimes[1] = 0.0; sectorPositions[0] = 0.0; sectorPositions[1] = 0.0; } void DriverRadarPositioner::setDriverData(DriverData *dd) { driverData = dd; } void DriverRadarPositioner::setStartupPosition() { int laps = EventData::getInstance().getEventInfo().laps; lapped = false; qualiOut = false; inPits = false; finished = false; wetTrack = false; sectorPositions[0] = 0; sectorPositions[1] = 0; //a very rough estimate ;) avgTime = 200 - 30 * log10(laps*laps); if (EventData::getInstance().getSessionRecords().getFastestLap().getTime().isValid()) avgTime = EventData::getInstance().getSessionRecords().getFastestLap().getTime().toDouble(); //if it's raining, we add 10 seconds if (EventData::getInstance().getWeather().getWetDry().getValue() == 1) avgTime += 10; //if SC is on track, we add 1 minute if (EventData::getInstance().getFlagStatus() == LTPackets::SAFETY_CAR_DEPLOYED) avgTime += 60; if (driverData && (driverData->isInPits() || driverData->isRetired())) { inPits = true; calculatePitPosition(); } else if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT && (!EventData::getInstance().isSessionStarted() || !driverData->getLastLap().getSectorTime(1).isValid())) { inPits = false; currentDeg = 360 - driverData->getPosition()*2; currentLapTime = -(avgTime-(avgTime * currentDeg) / 360); } else { currentLapTime = 0; for (int i = 0; i < 3; ++i) currentLapTime += driverData->getLastLap().getSectorTime(i+1).toDouble(); calculatePosition(); } } void DriverRadarPositioner::update() { if (startingNewLap && driverData && driverData->getLastLap().getSectorTime(3).isValid()) { currSector = 1; currentLapTime = 0; currentDeg = 0; calculateAvgs(); startingNewLap = false; } // else { if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT && driverData->getLastLap().getSectorTime(3).isValid() && EventData::getInstance().getCompletedLaps() == EventData::getInstance().getEventInfo().laps && (finished || fabs(maxDeg() - currentDeg) < 5)) { currentDeg = 0; finished = true; inPits = true; calculatePitPosition(); } else if (driverData->isInPits() || driverData->isRetired() || (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT && EventData::getInstance().getFlagStatus() == LTPackets::RED_FLAG)) { inPits = true; finished = false; calculatePitPosition(); } else { if (inPits) calculatePitOutPosition(); inPits = false; finished = false; calculatePosition(); } } if (!driverData->getLastLap().getSectorTime(3).isValid()) { startingNewLap = true; } } void DriverRadarPositioner::calculatePosition() { EventData &ev = EventData::getInstance(); if (!ev.isSessionStarted()) return; if (/*driverData->getLastLap().getTime().toString() != "OUT" &&*/ currentDeg > 0) { if (driverData->getLastLap().getSectorTime(1).isValid() && ((ev.getEventType() == LTPackets::RACE_EVENT && driverData->getColorData().lapTimeColor() == LTPackets::YELLOW) || (!driverData->getLastLap().getSectorTime(2).isValid() || !driverData->getLastLap().getSectorTime(3).isValid())) && currSector == 1) { currSector = 2; if (sectorPositions[0] != 0) { currentDeg = sectorPositions[0]; // int time = 360*currentLapTime / currentDeg; // avgTime = (avgTime + time) / 2; // currentLapTime = currentDeg * avgTime / 360; } // currentDeg += 360.0 / (double)avgTime; } else if (driverData->getLastLap().getSectorTime(2).isValid() && !driverData->getLastLap().getSectorTime(3).isValid() && currSector == 2 && driverData->getLastLap().getTime().toString() != "OUT") { currSector = 3; if (sectorPositions[1] != 0) { currentDeg = sectorPositions[1]; // int time = 360*currentLapTime / currentDeg; // avgTime = (avgTime + time) / 2; // currentLapTime = currentDeg * avgTime / 360; } } else { // if (driverData->getLastLap().getSectorTime(1).isValid()) // { // sumSectors += driverData->getLastLap().getSectorTime(1).toDouble(); // if (driverData->getLastLap().getSectorTime(2).isValid()) // sumSectors += driverData->getLastLap().getSectorTime(2).toDouble(); // if (currentLapTime < sumSectors) // currentLapTime = sumSectors; // } currentDeg += (360.0 / avgTime) / speed; //(360 * currentLapTime) / avgTime; } } else { // if (currentLapTime < 0) // currentDeg = (360 * (avgTime + currentLapTime)) / avgTime; // else currentDeg += (360.0 / avgTime) / speed; // currentDeg = (360 * currentLapTime) / avgTime; } } void DriverRadarPositioner::calculatePitPosition() { // int halfDrv = EventData::getInstance().getDriversData().size() / 2; // if (driverData->getCarID()-1 < halfDrv) // currentDeg = (halfDrv - driverData->getCarID()-1) * 5; // else // currentDeg = 360 - (driverData->getCarID()-1-halfDrv) * 5; int no = driverData->getNumber() - 1; if (no > 12) no -= 1; currentDeg = no * 7.75; EventData &ev = EventData::getInstance(); if (ev.getEventType() == LTPackets::QUALI_EVENT && ((ev.getQualiPeriod() == 2 && driverData->getPosition() > 17) || (ev.getQualiPeriod() == 3 && driverData->getPosition() > 10))) qualiOut = true; } bool DriverRadarPositioner::isSelected(QPoint p) { QPoint coord = getCoordinates(); if (inPits) { if ((abs(p.x() - coord.x())) <= 13 && (abs(coord.y() - p.y()) <= 10)) return true; if ((p.y() - coord.y() >= 0) && (p.y() - coord.y() <= 16) && (coord.x() - p.x() >= 12) && (coord.x() - p.x() <= 48)) return true; } else if ((abs(p.x() - coord.x())) <= 13 && ((coord.y() - p.y() <= 13) && (p.y() - coord.y() <= 26))) return true; return false; } void DriverRadarPositioner::calculateAvgs() { if (driverData) { double sumT = 0, sumS1 = 0, sumS2 = 0; int k = 0, ks1=0, ks2=0; LapData last = driverData->getLastLap(); if (!driverData->getLapData().isEmpty()) last = driverData->getLapData().last(); int i = driverData->getLapData().size()-1; //if the current lap is a second lap out of pits, synchronization has to be done to the best lap, not the last which was slow due to the pit stop if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT && i > 0 && (driverData->getLapData()[i-1].getRaceLapExtraData().isPitLap() || driverData->getLapData()[i-1].getRaceLapExtraData().isSCLap()) && !last.getRaceLapExtraData().isPitLap() && !last.getRaceLapExtraData().isSCLap()) last = driverData->getSessionRecords().getBestLap(); //if the session wasn't dry, durig quali and fp avg time will be calculated using last lap, not the best one if (EventData::getInstance().getEventType() != LTPackets::RACE_EVENT && !wetTrack && EventData::getInstance().getWeather().getWetDry().getValue() < 1) wetTrack = true; for (i = driverData->getLapData().size()-1; i >= driverData->getLapData().size()-4 && i >= 0; --i) { LapData ld = driverData->getLapData()[i]; if ((EventData::getInstance().getEventType() != LTPackets::RACE_EVENT) && !wetTrack) last = driverData->getSessionRecords().getBestLap(); if (ld.getTime().isValid() && (ld.getRaceLapExtraData().isSCLap() == last.getRaceLapExtraData().isSCLap()) && (fabs(ld.getTime().toDouble() - last.getTime().toDouble()) < 5)) { sumT += ld.getTime().toDouble(); ++k; } if (ld.getSectorTime(1).isValid() && fabs(ld.getSectorTime(1).toDouble()-last.getSectorTime(1).toDouble()) < 5) { sumS1 += ld.getSectorTime(1).toDouble(); ++ks1; } if (ld.getSectorTime(2).isValid() && fabs(ld.getSectorTime(2).toDouble()-last.getSectorTime(2).toDouble()) < 5) { sumS2 += ld.getSectorTime(2).toDouble(); ++ks2; } } // if (EventData::getInstance().getSessionRecords().getFastestLap().getTime().isValid()) // { // avgTime = EventData::getInstance().getSessionRecords().getFastestLap().getTime().toDouble(); // int drvNo = EventData::getInstance().getSessionRecords().getFastestLap().getNumber(); // int lapNo = EventData::getInstance().getSessionRecords().getFastestLap().getLapNumber(); // DriverData *dd = EventData::getInstance().getDriverDataPtr(drvNo); // if (dd) // { // LapData ld = dd->getLapData(lapNo); // double s1 = ld.getSectorTime(1).toDouble(); // double s2 = ld.getSectorTime(2).toDouble(); // if (s1 != 0 && s2 != 0) // { // sectorPositions[0] = (360 * s1) / avgTime; // sectorPositions[1] = (360 * (s1 + s2)) / avgTime; // } // } // } if (sumT != 0 && k > 0) avgTime = sumT / k; if (sumS1 != 0 && ks1 > 0 && sumS2 != 0 && ks2 > 0) { avgSectorTimes[0] = sumS1 / ks1; sectorPositions[0] = (360.0 * avgSectorTimes[0]) / avgTime; avgSectorTimes[1] = sumS2 / ks2; sectorPositions[1] = (360.0 * (avgSectorTimes[1] + avgSectorTimes[0])) / avgTime; } if (driverData->getPosition() != 1 && driverData->getLastLap().getGap().contains("L")) lapped = true; else lapped = false; if (driverData->getLastLap().getRaceLapExtraData().isPitLap() || driverData->isRetired()) inPits = true; else inPits = false; if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT && driverData->getLastLap().getSectorTime(3).isValid() && EventData::getInstance().getCompletedLaps() == EventData::getInstance().getEventInfo().laps) avgTime += 60; } } QPoint DriverRadarPositioner::getCoordinates() { double r = radarR; if (inPits/* && !qualiOut*/) r = radarPitR; else if (lapped/* || qualiOut*/) r = radarLappedR; double x = radarX, y = radarY - r; if (currentDeg > 0) { double alpha = currentDeg / 360 * 2 * M_PI;// - quarter * 90; x = radarX + /*cos(currentDeg)/fabs(cos(currentDeg)) **/ sin(alpha) * r; y = radarY - /*sin(currentDeg)/fabs(sin(currentDeg)) **/ cos(alpha) * r; } return QPoint(x, y); } void DriverRadarPositioner::paint(QPainter *p, bool selected) { if (!driverData || driverData->getCarID() < 1) return; LTPackets::EventType eType = EventData::getInstance().getEventType(); if (!excluded && (eType != LTPackets::RACE_EVENT || !driverData->isRetired())) { QPoint point = getCoordinates(); QColor drvColor = ColorsManager::getInstance().getCarColor(driverData->getNumber()); p->setBrush(QBrush(drvColor)); QPen pen(drvColor); if (driverData->getPosition() == 1) { pen.setColor(ColorsManager::getInstance().getDefaultColor(LTPackets::GREEN)); pen.setWidth(3); } if (driverData->isRetired() || qualiOut) { pen.setColor(QColor(255, 0, 0)); pen.setWidth(3); } if (selected) { pen.setColor(ColorsManager::getInstance().getDefaultColor(LTPackets::YELLOW)); pen.setWidth(3); } p->setPen(pen); QPixmap helmet = ImagesFactory::getInstance().getHelmetsFactory().getHelmet(driverData->getNumber(), 24); p->drawPixmap(point.x()-15, point.y()-15, helmet); p->setFont(QFont("Arial", 8, 75)); QString number = SeasonData::getInstance().getDriverShortName(driverData->getDriverName());//QString::number(driverData->getNumber()); p->setBrush(drvColor); if (inPits) // p->drawRoundedRect(point.x()-15, point.y()-8, helmet.width()-4, 14, 4, 4); p->drawRoundedRect(point.x()-16-helmet.width(), point.y(), helmet.width(), 14, 4, 4); else p->drawRoundedRect(point.x()-12, point.y()+15, helmet.width(), 14, 4, 4); p->setPen(ColorsManager::getInstance().getColor(LTPackets::BACKGROUND)); int numX = point.x() - 18 + p->fontMetrics().width(number)/2; int numY = point.y() + 20 + p->fontMetrics().height()/2; // int numX = point.x() - 15 + p->fontMetrics().width(number)/2; // int numY = point.y() - 2 + p->fontMetrics().height()/2; if (inPits) { numX = point.x() - helmet.width() - 22 + p->fontMetrics().width(number)/2; numY = point.y() + 5 + p->fontMetrics().height()/2; } p->drawText(numX, numY, number); // p->setPen(QColor(20, 20, 20)); // QString name = SeasonData::getInstance().getDriverShortName(driverData->getDriverName()); // int numX = point.x() - p->fontMetrics().width(name)/2; // int numY = point.y() + 12 - p->fontMetrics().height()/2; // p->setFont(QFont("Arial", 10, 75)); // p->drawText(numX, numY, name); } }
zywhlc-f1lt
src/tools/driverradarpositioner.cpp
C++
gpl3
16,489
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef SESSIONANALYSISWIDGET_H #define SESSIONANALYSISWIDGET_H #include <QtGui/QWidget> #include <QIcon> #include <QPair> #include <QSettings> #include "ui_sessionanalysiswidget.h" #include "../core/colorsmanager.h" #include "../core/eventdata.h" class SessionAnalysisWidget : public QWidget { Q_OBJECT public: SessionAnalysisWidget(QWidget *parent = 0); ~SessionAnalysisWidget(); void setupTables(); void resizeTables(); protected: void resizeEvent(QResizeEvent *); void keyPressEvent(QKeyEvent *); public slots: void selectDriversClicked(); void exec(); void setupColors(); void update(bool repaintCharts = true); void gatherData(); bool driverChecked(int no); void setDriverChecked(int no, bool checked); void onZoomChanged(int, int, double, double); void setupBoxes(); void setupIcons(const QList<QColor> &colors); QIcon getDriverIcon(int no); void resetView(); bool lapInWindow(int i); void saveSettings(QSettings &settings); void loadSettings(QSettings &settings); void onSplitterMoved(int pos, int index); private slots: void on_buttonBox_clicked(QAbstractButton *button); void on_pushButton_2_clicked(); void on_top10pushButton_clicked(); void on_qualiTabWidget_currentChanged(int index); private: QTableWidgetItem* setItem(QTableWidget *table, int row, int col, QString text = "", Qt::ItemFlags flags = Qt::NoItemFlags, int align = Qt::AlignCenter, QColor textColor = ColorsManager::getInstance().getColor(LTPackets::DEFAULT), QBrush background = QBrush()); Ui::SessionAnalysisWidgetClass ui; QList<QCheckBox*> driverCheckBoxes; QList<QLabel*> driverLabels; bool selected; int first, last; double min, max; QList<LapData> lapDataArray; QList< QPair<int, QIcon> > driverIcons; bool top10only; }; #endif // SESSIONANALYSISWIDGET_H
zywhlc-f1lt
src/tools/sessionanalysiswidget.h
C++
gpl3
3,476
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LAPTIMECOMPARISONDIALOG_H #define LAPTIMECOMPARISONDIALOG_H #include <QComboBox> #include <QDialog> #include <QList> #include "../core/seasondata.h" #include "../charts/lapcompchart.h" #include "../net/packetparser.h" namespace Ui { class LapTimeComparisonDialog; } class LapTimeComparisonDialog : public QDialog { Q_OBJECT public: explicit LapTimeComparisonDialog(QWidget *parent = 0); ~LapTimeComparisonDialog(); void setFont(const QFont &); void loadDriversList(); int getNumber(int); void setCurrentDriver(int id); public slots: int exec(int currentCarId = 0); void show(int currentCarId = 0); void comboBoxValueChanged(int); void updateData(); void updateCharts(); void driverUpdated(const DriverData &dd) { for (int i = 0; i < 4; ++i) { if (dd.getCarID() == eventData.getDriverId(getNumber(i))) { updateData(); updateCharts(); return; } } } void updateData(const DataUpdates &dataUpdates) { for (int i = 0; i < 2; ++i) { if (dataUpdates.driverIds.contains(eventData.getDriverId(getNumber(i)))) { updateData(); updateCharts(); return; } } } protected: void resizeEvent(QResizeEvent *); void keyPressEvent(QKeyEvent *); private: Ui::LapTimeComparisonDialog *ui; QComboBox *comboBox[4]; LapCompChart *lapCompChart; QColor color[4]; QList<QPixmap> *smallCarImg; EventData &eventData; int thumbnailsSize; }; #endif // LAPTIMECOMPARISONDIALOG_H
zywhlc-f1lt
src/tools/laptimecomparisondialog.h
C++
gpl3
3,243
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #include "laptimecomparisondialog.h" #include "ui_laptimecomparisondialog.h" #include <algorithm> #include <QClipboard> #include <QDebug> #include <QKeyEvent> #include <QStringList> #include <QList> #include <QLabel> #include <QResizeEvent> #include <QScrollBar> #include <cmath> #include "../core/colorsmanager.h" #include "../main_gui/ltitemdelegate.h" LapTimeComparisonDialog::LapTimeComparisonDialog(QWidget *parent) : QDialog(parent, Qt::Window), ui(new Ui::LapTimeComparisonDialog), eventData(EventData::getInstance()), thumbnailsSize(150) { ui->setupUi(this); comboBox[0] = ui->comboBox1; comboBox[1] = ui->comboBox2; comboBox[2] = ui->comboBox3; comboBox[3] = ui->comboBox4; loadDriversList(); lapCompChart = new LapCompChart(this); connect(ui->comboBox1, SIGNAL(currentIndexChanged(int)), this, SLOT(comboBoxValueChanged(int))); connect(ui->comboBox2, SIGNAL(currentIndexChanged(int)), this, SLOT(comboBoxValueChanged(int))); connect(ui->comboBox3, SIGNAL(currentIndexChanged(int)), this, SLOT(comboBoxValueChanged(int))); connect(ui->comboBox4, SIGNAL(currentIndexChanged(int)), this, SLOT(comboBoxValueChanged(int))); ui->tableWidget->setItemDelegate(new LTItemDelegate(this)); ui->tableWidget->setColumnWidth(0, 30); ui->tableWidget->setColumnWidth(1, 150); ui->tableWidget->setColumnWidth(2, 150); ui->tableWidget->setColumnWidth(3, 150); ui->tableWidget->setColumnWidth(4, 150); ui->chartsTableWidget->setColumnWidth(0, 170); ui->chartsTableWidget->setColumnWidth(1, 170); ui->chartsTableWidget->setColumnWidth(2, 170); ui->chartsTableWidget->setColumnWidth(3, 170); ui->chartsTableWidget->insertRow(0); ui->chartsTableWidget->setRowHeight(0, 20); ui->chartsTableWidget->insertRow(1); ui->chartsTableWidget->setRowHeight(1, 50); QTableWidgetItem *item; for (int j = 0; j < 4; ++j) { item = new QTableWidgetItem(); item->setFlags(Qt::NoItemFlags); item->setTextAlignment(Qt::AlignCenter); ui->chartsTableWidget->setItem(0, j, item); } ui->chartsTableWidget->insertRow(2); ui->chartsTableWidget->setCellWidget(2, 0, lapCompChart); ui->chartsTableWidget->setSpan(2, 0, 1, 4); ui->chartsTableWidget->setRowHeight(2, 500); ui->tableWidget->insertRow(0); item = new QTableWidgetItem("Lap"); item->setFlags(Qt::NoItemFlags); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setTextColor(ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); ui->tableWidget->setItem(0, 0, item); QLabel *lab = new QLabel(); ui->tableWidget->setCellWidget(0, 1, lab); lab->setAlignment(Qt::AlignCenter); lab = new QLabel(); ui->tableWidget->setCellWidget(0, 2, lab); lab->setAlignment(Qt::AlignCenter); lab = new QLabel(); ui->tableWidget->setCellWidget(0, 3, lab); lab->setAlignment(Qt::AlignCenter); lab = new QLabel(); ui->tableWidget->setCellWidget(0, 4, lab); lab->setAlignment(Qt::AlignCenter); ui->tableWidget->setRowHeight(0, 50); } LapTimeComparisonDialog::~LapTimeComparisonDialog() { delete ui; } void LapTimeComparisonDialog::loadDriversList() { comboBox[0]->clear(); comboBox[1]->clear(); comboBox[2]->clear(); comboBox[3]->clear(); if (comboBox[0]->itemText(1) == "")// && eventData.driversData[0].driver != "") { QStringList list = SeasonData::getInstance().getDriversList(); if (list.size() > 1) { comboBox[0]->addItems(list); comboBox[1]->addItems(list); comboBox[2]->addItems(list); comboBox[3]->addItems(list); } } // comboBox[0]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[1]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[2]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[3]->addItems(SeasonData::getInstance().getDriversList()); /*smallCarImg = */ImagesFactory::getInstance().getCarThumbnailsFactory().loadCarThumbnails(thumbnailsSize); } void LapTimeComparisonDialog::updateData() { int scrollBarPosition = ui->tableWidget->verticalScrollBar()->sliderPosition(); QItemSelectionModel * selection = ui->tableWidget->selectionModel(); // for (int i = ui->tableWidget->rowCount()-1; i >= 0; --i) // ui->tableWidget->removeRow(i); QTableWidgetItem *item; int firstLap = 99, lastLap = 0; int index[4]; QString wTitle = "Lap time comparison: "; for (int i = 0; i < 4; ++i) { index[i] = 0; int idx = eventData.getDriverId(getNumber(i)); if (idx > 0) { if (i > 0) wTitle += " - "; wTitle += eventData.getDriversData()[idx-1].getDriverName(); if(!eventData.getDriversData()[idx-1].getLapData().isEmpty()) { if (eventData.getDriversData()[idx-1].getLapData()[0].getLapNumber() < firstLap) firstLap = eventData.getDriversData()[idx-1].getLapData()[0].getLapNumber(); if (eventData.getDriversData()[idx-1].getLapData().last().getLapNumber() > lastLap) lastLap = eventData.getDriversData()[idx-1].getLapData().last().getLapNumber(); } DriverData &dd = eventData.getDriversData()[idx-1]; QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); lab->setPixmap(ImagesFactory::getInstance().getCarThumbnailsFactory().getCarThumbnail(dd.getNumber(), thumbnailsSize));//eventData.carImages[idx].scaledToWidth(120, Qt::SmoothTransformation)); } else { QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); lab->clear(); } } setWindowTitle(wTitle); // ui->tableWidget->insertRow(0); // ui->tableWidget->setRowHeight(0, 50); int j = 0, k = firstLap; for (; k <= lastLap; ++k, ++j) { int lapNo = lastLap - k + firstLap; LapTime laps[4]; if (ui->tableWidget->rowCount() <= j+1) ui->tableWidget->insertRow(j+1); item = ui->tableWidget->item(j+1, 0); if (!item) { item = new QTableWidgetItem(QString("%1.").arg(lapNo)); // item->setFlags(Qt::ItemIsSelectable); item->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter); item->setTextColor(ColorsManager::getInstance().getColor(LTPackets::DEFAULT)); ui->tableWidget->setItem(j+1, 0, item); } else item->setText(QString("%1.").arg(lapNo)); for (int i = 0; i < 4; ++i) { int idx = eventData.getDriverId(getNumber(i)); if (idx > 0 && !eventData.getDriversData()[idx-1].getLapData().isEmpty()) { //int lapIndex = (reversedOrder ? eventData.driversData[idx-1].lapData.size() - index[i] - 1 : index[i]); DriverData &dd = eventData.getDriversData()[idx-1]; LapData ld = dd.getLapData(lapNo); // if (j == 0) // { // int idx = (dd.number > 13 ? dd.number-2 : dd.number-1) / 2; // QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); // lab->setPixmap(smallCarImg[idx]);//eventData.carImages[idx].scaledToWidth(120, Qt::SmoothTransformation)); // } if (dd.getLapData().size() > index[i] && ld.getLapNumber() == lapNo && ld.getCarID() != -1) { laps[i] = ld.getTime(); item = ui->tableWidget->item(j+1, i+1); if (!item) { item = new QTableWidgetItem(ld.getTime()); item->setTextAlignment(Qt::AlignCenter); ui->tableWidget->setItem(j+1, i+1, item); } else item->setText(ld.getTime()); if (ld.getTime().toString() == "IN PIT") item->setText(item->text() + " (" + dd.getPitTime(ld.getLapNumber()) + ")"); ++index[i]; } else { item = ui->tableWidget->item(j+1, i+1); if (item) item->setText(""); } } else { if (j == 0) { // QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); // if (lab) // lab->clear(); } item = ui->tableWidget->item(j+1, i+1); if (item) item->setText(""); } } int bestIdx = DriverData::lapDiff(laps); if (bestIdx != -1) { for (int i = 0; i < 4; ++i) { if (i != bestIdx && laps[i].toString() != "" && laps[i].toString() != "IN PIT" && laps[i].toString() != "RETIRED" && !laps[i].toString().contains("LAP")) { item = ui->tableWidget->item(j+1, i+1); if (item) { item->setText(item->text() + " (+"+QString::number(laps[i].toDouble(), 'f', 3)+")"); double msecs[3]; int ji = 0; for (int j = 0; j < 4; ++j) { if (j != bestIdx) { if (laps[j].toString() != "") msecs[ji++] = laps[j].toMsecs(); else msecs[ji++] = 1000000; } } double maxGap = std::max(std::max(msecs[0], msecs[1]), msecs[2]); double minGap = std::min(std::min(msecs[0], msecs[1]), msecs[2]); LTPackets::Colors color = LTPackets::YELLOW; if (laps[i].toMsecs() == minGap) color = LTPackets::WHITE; else if (laps[i].toMsecs() == maxGap) color = LTPackets::RED; item->setTextColor(ColorsManager::getInstance().getColor(color)); } } else if (laps[i].toString() == "IN PIT" || laps[i].toString() == "RETIRED" || laps[i].toString().contains("LAP")) { item = ui->tableWidget->item(j+1, i+1); item->setTextColor(ColorsManager::getInstance().getColor(LTPackets::RED)); } } item = ui->tableWidget->item(j+1, bestIdx+1); if (item && laps[bestIdx].toString() != "IN PIT" && laps[bestIdx].toString() != "RETIRED" && !laps[bestIdx].toString().contains("LAP")) item->setTextColor(ColorsManager::getInstance().getColor(LTPackets::GREEN)); } ui->tableWidget->setRowHeight(j+1, 20); } for (int i = ui->tableWidget->rowCount()-1; i >= j+1; --i) ui->tableWidget->removeRow(i); ui->tableWidget->setSelectionModel(selection); ui->tableWidget->verticalScrollBar()->setSliderPosition(scrollBarPosition); } void LapTimeComparisonDialog::updateCharts() { DriverData *driverData[4] = {0, 0, 0, 0}; QString driver; for (int i = 0; i < 4; ++i) { int idx = eventData.getDriverId(getNumber(i)); if (idx > 0) { driver = eventData.getDriversData()[idx-1].getDriverName(); driverData[i] = &eventData.getDriversData()[idx-1]; // carIdx = (eventData.getDriversData()[idx-1].getNumber() > 13 ? // eventData.getDriversData()[idx-1].getNumber() - 2 : // eventData.getDriversData()[idx-1].getNumber() - 1) / 2; QTableWidgetItem *item = ui->chartsTableWidget->item(0, i); item->setText(driver); item->setTextColor(ColorsManager::getInstance().getCarColor(driverData[i]->getNumber())); // if (carIdx >= 0) { QLabel *lab = qobject_cast<QLabel*>(ui->chartsTableWidget->cellWidget(1, i)); if (!lab) { lab = new QLabel(); lab->setAlignment(Qt::AlignCenter); lab->setPixmap(ImagesFactory::getInstance().getCarThumbnailsFactory().getCarThumbnail(driverData[i]->getNumber(), thumbnailsSize));//eventData.carImages[carIdx].scaledToWidth(120, Qt::SmoothTransformation)); ui->chartsTableWidget->setCellWidget(1, i, lab); } else lab->setPixmap(ImagesFactory::getInstance().getCarThumbnailsFactory().getCarThumbnail(driverData[i]->getNumber(), thumbnailsSize));//eventData.carImages[carIdx].scaledToWidth(120, Qt::SmoothTransformation)); } } else { QTableWidgetItem *item = ui->chartsTableWidget->item(0, i); item->setText(""); QLabel *lab = qobject_cast<QLabel*>(ui->chartsTableWidget->cellWidget(1, i)); if (lab) lab->clear(); } } lapCompChart->setData(driverData); lapCompChart->repaint(); } void LapTimeComparisonDialog::show(int currentCarId) { // if (comboBox[0]->itemText(1) == "") // { // comboBox[0]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[1]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[2]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[3]->addItems(SeasonData::getInstance().getDriversList()); // } setCurrentDriver(currentCarId); for (int i = 0; i < 4; ++i) { QLabel *lab = qobject_cast<QLabel*>(ui->tableWidget->cellWidget(0, i+1)); if (lab) lab->clear(); } updateData(); updateCharts(); QDialog::show(); } int LapTimeComparisonDialog::exec(int currentCarId) { // if (comboBox[0]->itemText(1) == "") // { // comboBox[0]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[1]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[2]->addItems(SeasonData::getInstance().getDriversList()); // comboBox[3]->addItems(SeasonData::getInstance().getDriversList()); // } setCurrentDriver(currentCarId); updateData(); updateCharts(); return QDialog::exec(); } void LapTimeComparisonDialog::comboBoxValueChanged(int) { updateData(); updateCharts(); } void LapTimeComparisonDialog::resizeEvent(QResizeEvent *event) { for (int i = 0; i < 4; ++i) { ui->chartsTableWidget->setColumnWidth(i, (event->size().width()-40) / 4-5); ui->tableWidget->setColumnWidth(i+1, (event->size().width()-50) / 4 - 10); } int h = /*ui->chartsTableWidget->viewport()->height()-80;*/event->size().height() - 250; if (h < 200) h = 200; ui->chartsTableWidget->setRowHeight(2, h); } void LapTimeComparisonDialog::keyPressEvent(QKeyEvent *event) { if (ui->tabWidget->currentIndex() == 0 && event->key() == Qt::Key_C && event->modifiers() == Qt::ControlModifier) { QItemSelectionModel * selection = ui->tableWidget->selectionModel(); QModelIndexList indexes = selection->selectedIndexes(); if(indexes.size() < 1) return; // QModelIndex::operator < sorts first by row, then by column. // this is what we need qSort(indexes.begin(), indexes.end()); // You need a pair of indexes to find the row changes QModelIndex previous = indexes.first(); indexes.removeFirst(); QString selected_text; QModelIndex current; Q_FOREACH(current, indexes) { QVariant data = ui->tableWidget->model()->data(previous); QString text = data.toString(); // At this point `text` contains the text in one cell selected_text.append(text); // If you are at the start of the row the row number of the previous index // isn't the same. Text is followed by a row separator, which is a newline. if (current.row() != previous.row()) { selected_text.append(QLatin1Char('\n')); } // Otherwise it's the same row, so append a column separator, which is a tab. else { selected_text.append(QLatin1Char('\t')); } previous = current; } selected_text.append(ui->tableWidget->model()->data(current).toString()); selected_text.append(QLatin1Char('\n')); qApp->clipboard()->setText(selected_text); } if (event->key() == Qt::Key_Escape) close(); } void LapTimeComparisonDialog::setFont(const QFont &font) { ui->tableWidget->setFont(font); } void LapTimeComparisonDialog::setCurrentDriver(int id) { if (id != 0) { DriverData *dd = eventData.getDriverDataByIdPtr(id); if (dd != 0 && dd->getCarID() > 0) { int idx = comboBox[0]->findText(QString("%1 %2").arg(dd->getNumber()).arg(dd->getDriverName())); if (idx != -1) comboBox[0]->setCurrentIndex(idx); } } } int LapTimeComparisonDialog::getNumber(int i) { QString text = comboBox[i]->currentText(); int no = -1; int idx = text.indexOf(" "); if (idx != 0) { bool ok; no = text.left(idx).toInt(&ok); if (!ok) no = -1; } return no; }
zywhlc-f1lt
src/tools/laptimecomparisondialog.cpp
C++
gpl3
19,558
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef SESSIONTIMESWIDGET_H #define SESSIONTIMESWIDGET_H #include <QKeyEvent> #include <QSettings> #include <QTableWidgetItem> #include <QToolButton> #include <QWidget> #include "../core/colorsmanager.h" #include "../core/driverdata.h" #include "../core/seasondata.h" namespace Ui { class SessionTimesWidget; } class SessionTimesWidget : public QWidget { Q_OBJECT public: explicit SessionTimesWidget(QWidget *parent = 0); ~SessionTimesWidget(); void update(); void handleRaceEvent(); void handleQualiEvent(); void handlePracticeEvent(); void loadDriversList(); int getNumber(int row); QString getName(int row); void exec(); void removeRows(int row); void setFont(const QFont &); void saveSettings(QSettings &settings); void loadSettings(QSettings &settings); void saveCheckedArray(); void restoreCheckedArray(); protected: void keyPressEvent(QKeyEvent *); private slots: void onHeaderClicked(int); void onHeaderDoubleClicked(int); void on_closeButton_clicked(); void on_flagButton_clicked(); void on_driversListWidget_clicked(const QModelIndex &index); void on_relativeButton_toggled(bool checked); void on_driversListWidget_doubleClicked(const QModelIndex &index); void on_top10Button_toggled(bool checked); private: QTableWidgetItem* setItem(int row, int col, QString text = "", Qt::ItemFlags flags = Qt::NoItemFlags, int align = Qt::AlignCenter, QColor textColor = ColorsManager::getInstance().getColor(LTPackets::DEFAULT), QBrush background = QBrush()); Ui::SessionTimesWidget *ui; DriverData *selectedDriver; bool relativeTimes; QByteArray checkedArray; }; #endif // SESSIONTIMESWIDGET_H
zywhlc-f1lt
src/tools/sessiontimeswidget.h
C++
gpl3
3,313
/******************************************************************************* * * * F1LT - unofficial Formula 1 live timing application * * Copyright (C) 2012-2013 Mariusz Pilarek (pieczaro@gmail.com) * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 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. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * *******************************************************************************/ #ifndef LTFILESMANAGERDIALOG_H #define LTFILESMANAGERDIALOG_H #include <QDialog> #include <QProgressDialog> #include <QSettings> #include <QTreeWidgetItem> #include "../net/ltfilesmanager.h" namespace Ui { class LTFilesManagerDialog; } class LTFilesManagerDialog : public QDialog { Q_OBJECT public: explicit LTFilesManagerDialog(QWidget *parent = 0); ~LTFilesManagerDialog(); QString exec(); // QTreeWidgetItem *parseEntry(QTreeWidgetItem *parent, QString entry, const QStringList &onlineList); QStringList parseEntry(QString entry, const QStringList &onlineList); QString getSessionType(QString session); void downloadLTList(); void getLTListFromDisk(); void updateTree(const QStringList &onlineList); bool fileExists(QString &file, bool saveCurrent = true); void loadSettings(QSettings *); void saveSettings(QSettings *); public slots: void ltListObtained(QStringList); void ltFileObtained(QByteArray); void downloadProgress ( qint64 bytesReceived, qint64 bytesTotal ); void error (QNetworkReply::NetworkError code); private slots: void on_treeWidget_itemClicked(QTreeWidgetItem *item, int column); void on_refreshButton_clicked(); void on_playButton_clicked(); void on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column); void on_cancelButton_clicked(); private: Ui::LTFilesManagerDialog *ui; QSet<QString> ltList; LTFilesManager ltFilesManager; QProgressDialog *progress; QString currentFile; }; #endif // LTFILESMANAGERDIALOG_H
zywhlc-f1lt
src/tools/ltfilesmanagerdialog.h
C++
gpl3
3,124