FlatCAMApp.py 506 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.FlatCAMGUI import *
  36. from FlatCAMCommon import LoudDict
  37. from FlatCAMPostProc import load_postprocessors
  38. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  39. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  40. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  41. from FlatCAMProcess import *
  42. from FlatCAMWorkerStack import WorkerStack
  43. from flatcamGUI.VisPyVisuals import Color
  44. from vispy.gloo.util import _screenshot
  45. from vispy.io import write_png
  46. from flatcamTools import *
  47. import tclCommands
  48. import gettext
  49. import FlatCAMTranslation as fcTranslate
  50. import builtins
  51. if sys.platform == 'win32':
  52. import winreg
  53. fcTranslate.apply_language('strings')
  54. if '_' not in builtins.__dict__:
  55. _ = gettext.gettext
  56. # ########################################
  57. # # App ###
  58. # ########################################
  59. class App(QtCore.QObject):
  60. """
  61. The main application class. The constructor starts the GUI.
  62. """
  63. # Get Cmd Line Options
  64. cmd_line_shellfile = ''
  65. cmd_line_shellvar = ''
  66. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\nFlatCam.py --shellvar=<1,'C:\path',23>"
  67. try:
  68. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  69. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  70. "shellvar=",
  71. "multiprocessing-fork="])
  72. except getopt.GetoptError:
  73. print(cmd_line_help)
  74. sys.exit(2)
  75. for opt, arg in cmd_line_options:
  76. if opt == '-h':
  77. print(cmd_line_help)
  78. sys.exit()
  79. elif opt == '--shellfile':
  80. cmd_line_shellfile = arg
  81. elif opt == '--shellvar':
  82. cmd_line_shellvar = arg
  83. # ## Logging ###
  84. log = logging.getLogger('base')
  85. log.setLevel(logging.DEBUG)
  86. # log.setLevel(logging.WARNING)
  87. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  88. handler = logging.StreamHandler()
  89. handler.setFormatter(formatter)
  90. log.addHandler(handler)
  91. # ##########################################################################
  92. # ################## Version and VERSION DATE ##############################
  93. # ##########################################################################
  94. version = 8.97
  95. version_date = "2019/09/20"
  96. beta = True
  97. # current date now
  98. date = str(datetime.today()).rpartition('.')[0]
  99. date = ''.join(c for c in date if c not in ':-')
  100. date = date.replace(' ', '_')
  101. # URL for update checks and statistics
  102. version_url = "http://flatcam.org/version"
  103. # App URL
  104. app_url = "http://flatcam.org"
  105. # Manual URL
  106. manual_url = "http://flatcam.org/manual/index.html"
  107. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  108. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  109. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  110. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  111. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  112. # this variable will hold the project status
  113. # if True it will mean that the project was modified and not saved
  114. should_we_save = False
  115. # flag is True if saving action has been triggered
  116. save_in_progress = False
  117. # ###########################################################################
  118. # ############################# Signals ################################
  119. # ###########################################################################
  120. # Inform the user
  121. # Handled by:
  122. # * App.info() --> Print on the status bar
  123. inform = QtCore.pyqtSignal(str)
  124. app_quit = QtCore.pyqtSignal()
  125. # General purpose background task
  126. worker_task = QtCore.pyqtSignal(dict)
  127. # File opened
  128. # Handled by:
  129. # * register_folder()
  130. # * register_recent()
  131. # Note: Setting the parameters to unicode does not seem
  132. # to have an effect. Then are received as Qstring
  133. # anyway.
  134. # File type and filename
  135. file_opened = QtCore.pyqtSignal(str, str)
  136. # File type and filename
  137. file_saved = QtCore.pyqtSignal(str, str)
  138. # Percentage of progress
  139. progress = QtCore.pyqtSignal(int)
  140. plots_updated = QtCore.pyqtSignal()
  141. # Emitted by new_object() and passes the new object as argument, plot flag.
  142. # on_object_created() adds the object to the collection, plots on appropriate flag
  143. # and emits new_object_available.
  144. object_created = QtCore.pyqtSignal(object, bool, bool)
  145. # Emitted when a object has been changed (like scaled, mirrored)
  146. object_changed = QtCore.pyqtSignal(object)
  147. # Emitted after object has been plotted.
  148. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  149. object_plotted = QtCore.pyqtSignal(object)
  150. # Emitted when a new object has been added or deleted from/to the collection
  151. object_status_changed = QtCore.pyqtSignal(object, str)
  152. message = QtCore.pyqtSignal(str, str, str)
  153. # Emmited when shell command is finished(one command only)
  154. shell_command_finished = QtCore.pyqtSignal(object)
  155. # Emitted when multiprocess pool has been recreated
  156. pool_recreated = QtCore.pyqtSignal(object)
  157. # Emitted when an unhandled exception happens
  158. # in the worker task.
  159. thread_exception = QtCore.pyqtSignal(object)
  160. # used to signal that there are arguments for the app
  161. args_at_startup = QtCore.pyqtSignal(list)
  162. # a reusable signal to replot a list of objects
  163. # should be disconnected after use so it can be reused
  164. replot_signal = pyqtSignal(list)
  165. def __init__(self, user_defaults=True, post_gui=None):
  166. """
  167. Starts the application.
  168. :return: app
  169. :rtype: App
  170. """
  171. App.log.info("FlatCAM Starting...")
  172. self.main_thread = QtWidgets.QApplication.instance().thread()
  173. # ############################################################################
  174. # # ################# OS-specific ############################################
  175. # ############################################################################
  176. portable = False
  177. # Folder for user settings.
  178. if sys.platform == 'win32':
  179. # #########################################################################
  180. # Setup the listening thread for another instance launching with args #####
  181. # #########################################################################
  182. # make sure the thread is stored by using a self. otherwise it's garbage collected
  183. self.th = QtCore.QThread()
  184. self.th.start(priority=QtCore.QThread.LowestPriority)
  185. self.new_launch = ArgsThread()
  186. self.new_launch.open_signal[list].connect(self.on_startup_args)
  187. self.new_launch.moveToThread(self.th)
  188. self.new_launch.start.emit()
  189. from win32com.shell import shell, shellcon
  190. if platform.architecture()[0] == '32bit':
  191. App.log.debug("Win32!")
  192. else:
  193. App.log.debug("Win64!")
  194. # #########################################################################
  195. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  196. # #########################################################################
  197. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  198. try:
  199. with open(config_file, 'r') as f:
  200. try:
  201. for line in f:
  202. param = str(line).rpartition('=')
  203. if param[0] == 'portable':
  204. try:
  205. portable = eval(param[2])
  206. except NameError:
  207. portable = False
  208. except Exception as e:
  209. log.debug('App.__init__() -->%s' % str(e))
  210. return
  211. except FileNotFoundError:
  212. pass
  213. if portable is False:
  214. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  215. else:
  216. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  217. self.os = 'windows'
  218. else: # Linux/Unix/MacOS
  219. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  220. self.os = 'unix'
  221. # ##########################################################################
  222. # ################## Setup folders and files ###############################
  223. # ##########################################################################
  224. if not os.path.exists(self.data_path):
  225. os.makedirs(self.data_path)
  226. App.log.debug('Created data folder: ' + self.data_path)
  227. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  228. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  229. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  230. if not os.path.exists(self.postprocessorpaths):
  231. os.makedirs(self.postprocessorpaths)
  232. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  233. # create current_defaults.FlatConfig file if there is none
  234. try:
  235. f = open(self.data_path + '/current_defaults.FlatConfig')
  236. f.close()
  237. except IOError:
  238. App.log.debug('Creating empty current_defaults.FlatConfig')
  239. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  240. json.dump({}, f)
  241. f.close()
  242. # create factory_defaults.FlatConfig file if there is none
  243. try:
  244. f = open(self.data_path + '/factory_defaults.FlatConfig')
  245. f.close()
  246. except IOError:
  247. App.log.debug('Creating empty factory_defaults.FlatConfig')
  248. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  249. json.dump({}, f)
  250. f.close()
  251. try:
  252. f = open(self.data_path + '/recent.json')
  253. f.close()
  254. except IOError:
  255. App.log.debug('Creating empty recent.json')
  256. f = open(self.data_path + '/recent.json', 'w')
  257. json.dump([], f)
  258. f.close()
  259. try:
  260. fp = open(self.data_path + '/recent_projects.json')
  261. fp.close()
  262. except IOError:
  263. App.log.debug('Creating empty recent_projects.json')
  264. fp = open(self.data_path + '/recent_projects.json', 'w')
  265. json.dump([], fp)
  266. fp.close()
  267. # Application directory. CHDIR to it. Otherwise, trying to load
  268. # GUI icons will fail as their path is relative.
  269. # This will fail under cx_freeze ...
  270. self.app_home = os.path.dirname(os.path.realpath(__file__))
  271. App.log.debug("Application path is " + self.app_home)
  272. App.log.debug("Started in " + os.getcwd())
  273. # cx_freeze workaround
  274. if os.path.isfile(self.app_home):
  275. self.app_home = os.path.dirname(self.app_home)
  276. os.chdir(self.app_home)
  277. # #############################################################################
  278. # ##################### CREATE MULTIPROCESSING POOL ###########################
  279. # #############################################################################
  280. self.pool = Pool()
  281. # ##########################################################################
  282. # ################## Setting the Splash Screen #############################
  283. # ##########################################################################
  284. settings = QSettings("Open Source", "FlatCAM")
  285. if settings.contains("splash_screen"):
  286. show_splash = settings.value("splash_screen")
  287. else:
  288. settings.setValue('splash_screen', 1)
  289. # This will write the setting to the platform specific storage.
  290. del settings
  291. show_splash = 1
  292. if show_splash:
  293. splash_pix = QtGui.QPixmap('share/splash.png')
  294. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  295. # self.splash.setMask(splash_pix.mask())
  296. # move splashscreen to the current monitor
  297. desktop = QtWidgets.QApplication.desktop()
  298. screen = desktop.screenNumber(QtGui.QCursor.pos())
  299. current_screen_center = desktop.availableGeometry(screen).center()
  300. self.splash.move(current_screen_center - self.splash.rect().center())
  301. self.splash.show()
  302. self.splash.showMessage(_("FlatCAM is initializing ..."),
  303. alignment=Qt.AlignBottom | Qt.AlignLeft,
  304. color=QtGui.QColor("gray"))
  305. # #############################################################################
  306. # ##################### Initialize GUI ########################################
  307. # #############################################################################
  308. # FlatCAM colors used in plotting
  309. self.FC_light_green = '#BBF268BF'
  310. self.FC_dark_green = '#006E20BF'
  311. self.FC_light_blue = '#a5a5ffbf'
  312. self.FC_dark_blue = '#0000ffbf'
  313. QtCore.QObject.__init__(self)
  314. self.ui = FlatCAMGUI(self.version, self.beta, self)
  315. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  316. self.ui.final_save.connect(self.final_save)
  317. # #################################################################
  318. # ####################### SYS TRAY ################################
  319. # #################################################################
  320. self.parent_w = QtWidgets.QWidget()
  321. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32.png'), parent=self.parent_w)
  322. # #############################################################################
  323. # ############################## Data #########################################
  324. # #############################################################################
  325. self.recent = []
  326. self.recent_projects = []
  327. self.clipboard = QtWidgets.QApplication.clipboard()
  328. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  329. self.project_filename = None
  330. self.toggle_units_ignore = False
  331. # self.defaults_form = PreferencesUI()
  332. # when adding entries here read the comments in the method found bellow named:
  333. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  334. self.defaults_form_fields = {
  335. # General App
  336. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  337. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  338. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  339. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  340. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  341. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  342. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  343. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  344. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  345. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  346. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  347. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  348. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  349. # General GUI Preferences
  350. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  351. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  352. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  353. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  354. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  355. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  356. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  357. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  358. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  359. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  360. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  361. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  362. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  363. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  364. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  365. # General GUI Settings
  366. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  367. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  368. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  369. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  370. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  371. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  372. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  373. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  374. # Gerber General
  375. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  376. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  377. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  378. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  379. # Gerber Options
  380. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  381. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  382. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  383. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  384. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  385. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  386. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  387. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  388. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  389. # Gerber Advanced Options
  390. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  391. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  392. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  393. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  394. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  395. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  396. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  397. # Gerber Export
  398. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  399. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  400. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  401. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  402. # Gerber Editor
  403. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  404. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  405. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  406. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  407. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  408. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  409. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  410. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  411. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  412. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  413. "gerber_editor_circ_angle":
  414. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  415. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  416. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  417. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  418. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  419. # Excellon General
  420. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  421. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  422. "excellon_format_upper_in":
  423. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  424. "excellon_format_lower_in":
  425. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  426. "excellon_format_upper_mm":
  427. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  428. "excellon_format_lower_mm":
  429. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  430. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  431. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  432. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  433. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  434. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  435. # Excellon Options
  436. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  437. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  438. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  439. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  440. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  441. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  442. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  443. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  444. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  445. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  446. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  447. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  448. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  449. # Excellon Advanced Options
  450. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  451. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  452. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  453. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  454. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  455. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  456. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  457. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  458. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  459. # Excellon Export
  460. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  461. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  462. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  463. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  464. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  465. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  466. # Excellon Editor
  467. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  468. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  469. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  470. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  471. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  472. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  473. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  474. "excellon_editor_circ_angle":
  475. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  476. # Excellon Slots
  477. "excellon_editor_slot_direction":
  478. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  479. "excellon_editor_slot_angle":
  480. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  481. "excellon_editor_slot_length":
  482. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  483. # Excellon Slots
  484. "excellon_editor_slot_array_size":
  485. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  486. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  487. "excellon_editor_slot_lin_pitch":
  488. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  489. "excellon_editor_slot_lin_angle":
  490. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  491. "excellon_editor_slot_circ_dir":
  492. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  493. "excellon_editor_slot_circ_angle":
  494. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  495. # Geometry General
  496. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  497. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  498. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  499. # Geometry Options
  500. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  501. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  502. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  503. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  504. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  505. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  506. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  507. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  508. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  509. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  510. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  511. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  512. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  513. # Geometry Advanced Options
  514. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  515. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  516. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  517. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  518. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  519. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  520. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  521. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  522. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  523. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  524. # Geometry Editor
  525. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  526. # CNCJob General
  527. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  528. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  529. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  530. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  531. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  532. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  533. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  534. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  535. # CNC Job Options
  536. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  537. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  538. # CNC Job Advanced Options
  539. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  540. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  541. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  542. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  543. # NCC Tool
  544. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  545. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  546. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  547. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  548. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  549. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  550. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  551. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  552. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  553. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  554. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  555. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  556. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  557. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  558. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  559. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  560. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  561. # CutOut Tool
  562. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  563. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  564. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  565. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  566. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  567. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  568. # Paint Area Tool
  569. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  570. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  571. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  572. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  573. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  574. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  575. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  576. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  577. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  578. # 2-sided Tool
  579. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  580. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  581. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  582. # Film Tool
  583. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  584. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  585. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  586. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  587. # Panelize Tool
  588. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  589. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  590. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  591. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  592. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  593. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  594. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  595. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  596. # Calculators Tool
  597. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  598. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  599. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  600. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  601. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  602. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  603. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  604. # Transformations Tool
  605. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  606. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  607. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  608. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  609. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  610. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  611. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  612. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  613. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  614. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  615. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  616. # SolderPaste Dispensing Tool
  617. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  618. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  619. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  620. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  621. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  622. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  623. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  624. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  625. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  626. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  627. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  628. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  629. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  630. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  631. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  632. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  633. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  634. # Utilities
  635. # File associations
  636. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  637. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  638. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  639. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  640. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  641. }
  642. # ############################
  643. # ### LOAD POSTPROCESSORS ####
  644. # ############################
  645. self.postprocessors = load_postprocessors(self)
  646. for name in list(self.postprocessors.keys()):
  647. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  648. if name.partition('_')[0] == 'Paste':
  649. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  650. continue
  651. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  652. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  653. if name == 'hpgl':
  654. continue
  655. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  656. # ############################
  657. # ### LOAD LANGUAGES ####
  658. # ############################
  659. self.languages = fcTranslate.load_languages()
  660. for name in sorted(self.languages.values()):
  661. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  662. self.defaults = LoudDict()
  663. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  664. self.defaults.update({
  665. # Global APP Preferences
  666. "first_run": True,
  667. "units": "IN",
  668. "global_serial": 0,
  669. "global_stats": {},
  670. "global_tabs_detachable": True,
  671. "global_app_level": 'b',
  672. "global_portable": False,
  673. "global_language": 'English',
  674. "global_version_check": True,
  675. "global_send_stats": True,
  676. "global_pan_button": '2',
  677. "global_mselect_key": 'Control',
  678. "global_project_at_startup": False,
  679. "global_project_autohide": True,
  680. "global_toggle_tooltips": True,
  681. "global_worker_number": 2,
  682. "global_tolerance": 0.01,
  683. "global_open_style": True,
  684. "global_delete_confirmation": True,
  685. "global_compression_level": 3,
  686. "global_save_compressed": True,
  687. # Global GUI Preferences
  688. "global_gridx": 0.0393701,
  689. "global_gridy": 0.0393701,
  690. "global_snap_max": 0.001968504,
  691. "global_workspace": False,
  692. "global_workspaceT": "A4P",
  693. "global_grid_context_menu": {
  694. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  695. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  696. },
  697. "global_plot_fill": '#BBF268BF',
  698. "global_plot_line": '#006E20BF',
  699. "global_sel_fill": '#a5a5ffbf',
  700. "global_sel_line": '#0000ffbf',
  701. "global_alt_sel_fill": '#BBF268BF',
  702. "global_alt_sel_line": '#006E20BF',
  703. "global_draw_color": '#FF0000',
  704. "global_sel_draw_color": '#0000FF',
  705. "global_proj_item_color": '#000000',
  706. "global_proj_item_dis_color": '#b7b7cb',
  707. "global_toolbar_view": 511,
  708. "global_background_timeout": 300000, # Default value is 5 minutes
  709. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  710. # (python trace only for unknown errors),
  711. # 1 = show trace(show trace always),
  712. # 2 = (For the future).
  713. # Persistence
  714. "global_last_folder": None,
  715. "global_last_save_folder": None,
  716. # Default window geometry
  717. "global_def_win_x": 100,
  718. "global_def_win_y": 100,
  719. "global_def_win_w": 1024,
  720. "global_def_win_h": 650,
  721. "global_def_notebook_width": 1,
  722. # Constants...
  723. "global_defaults_save_period_ms": 20000, # Time between default saves.
  724. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  725. "global_shell_at_startup": False, # Show the shell at startup.
  726. "global_recent_limit": 10, # Max. items in recent list.
  727. "fit_key": 'V',
  728. "zoom_out_key": '-',
  729. "zoom_in_key": '=',
  730. "grid_toggle_key": 'G',
  731. "global_zoom_ratio": 1.5,
  732. "global_point_clipboard_format": "(%.4f, %.4f)",
  733. "global_zdownrate": None,
  734. # General GUI Settings
  735. "global_hover": False,
  736. "global_selection_shape": True,
  737. "global_layout": "compact",
  738. # Gerber General
  739. "gerber_plot": True,
  740. "gerber_solid": True,
  741. "gerber_multicolored": False,
  742. "gerber_circle_steps": 128,
  743. "gerber_use_buffer_for_union": True,
  744. # Gerber Options
  745. "gerber_isotooldia": 0.00787402,
  746. "gerber_isopasses": 1,
  747. "gerber_isooverlap": 0.00393701,
  748. "gerber_milling_type": "cl",
  749. "gerber_combine_passes": False,
  750. "gerber_noncoppermargin": 0.00393701,
  751. "gerber_noncopperrounded": False,
  752. "gerber_bboxmargin": 0.00393701,
  753. "gerber_bboxrounded": False,
  754. # Gerber Advanced Options
  755. "gerber_aperture_display": False,
  756. "gerber_aperture_scale_factor": 1.0,
  757. "gerber_aperture_buffer_factor": 0.0,
  758. "gerber_follow": False,
  759. "gerber_buffering": "full",
  760. "gerber_simplification": False,
  761. "gerber_simp_tolerance": 0.0005,
  762. # Gerber Export
  763. "gerber_exp_units": 'IN',
  764. "gerber_exp_integer": 2,
  765. "gerber_exp_decimals": 4,
  766. "gerber_exp_zeros": 'L',
  767. # Gerber Editor
  768. "gerber_editor_sel_limit": 30,
  769. "gerber_editor_newcode": 10,
  770. "gerber_editor_newsize": 0.8,
  771. "gerber_editor_newtype": 'C',
  772. "gerber_editor_newdim": "0.5, 0.5",
  773. "gerber_editor_array_size": 5,
  774. "gerber_editor_lin_axis": 'X',
  775. "gerber_editor_lin_pitch": 1,
  776. "gerber_editor_lin_angle": 0.0,
  777. "gerber_editor_circ_dir": 'CW',
  778. "gerber_editor_circ_angle": 0.0,
  779. "gerber_editor_scale_f": 1.0,
  780. "gerber_editor_buff_f": 0.1,
  781. "gerber_editor_ma_low": 0.0,
  782. "gerber_editor_ma_high": 1.0,
  783. # Excellon General
  784. "excellon_plot": True,
  785. "excellon_solid": True,
  786. "excellon_format_upper_in": 2,
  787. "excellon_format_lower_in": 4,
  788. "excellon_format_upper_mm": 3,
  789. "excellon_format_lower_mm": 3,
  790. "excellon_zeros": "L",
  791. "excellon_units": "INCH",
  792. "excellon_update": True,
  793. "excellon_optimization_type": 'B',
  794. "excellon_search_time": 3,
  795. # Excellon Options
  796. "excellon_drillz": -0.0590551,
  797. "excellon_travelz": 0.0787402,
  798. "excellon_endz": 0.5,
  799. "excellon_feedrate": 3.14961,
  800. "excellon_spindlespeed": None,
  801. "excellon_dwell": False,
  802. "excellon_dwelltime": 1,
  803. "excellon_toolchange": False,
  804. "excellon_toolchangez": 0.5,
  805. "excellon_ppname_e": 'default',
  806. "excellon_tooldia": 0.0314961,
  807. "excellon_slot_tooldia": 0.0708661,
  808. "excellon_gcode_type": "drills",
  809. # Excellon Advanced Options
  810. "excellon_offset": 0.0,
  811. "excellon_toolchangexy": "0.0, 0.0",
  812. "excellon_startz": None,
  813. "excellon_feedrate_rapid": 31.4961,
  814. "excellon_z_pdepth": -0.02,
  815. "excellon_feedrate_probe": 3.14961,
  816. "excellon_spindledir": 'CW',
  817. "excellon_f_plunge": False,
  818. "excellon_f_retract": False,
  819. # Excellon Export
  820. "excellon_exp_units": 'INCH',
  821. "excellon_exp_format": 'ndec',
  822. "excellon_exp_integer": 2,
  823. "excellon_exp_decimals": 4,
  824. "excellon_exp_zeros": 'LZ',
  825. "excellon_exp_slot_type": 'routing',
  826. # Excellon Editor
  827. "excellon_editor_sel_limit": 30,
  828. "excellon_editor_newdia": 0.039,
  829. "excellon_editor_array_size": 5,
  830. "excellon_editor_lin_dir": 'X',
  831. "excellon_editor_lin_pitch": 0.1,
  832. "excellon_editor_lin_angle": 0.0,
  833. "excellon_editor_circ_dir": 'CW',
  834. "excellon_editor_circ_angle": 12,
  835. # Excellon Slots
  836. "excellon_editor_slot_direction": 'X',
  837. "excellon_editor_slot_angle": 0.0,
  838. "excellon_editor_slot_length": 5.0,
  839. # Excellon Slot Array
  840. "excellon_editor_slot_array_size": 5,
  841. "excellon_editor_slot_lin_dir": 'X',
  842. "excellon_editor_slot_lin_pitch": 0.1,
  843. "excellon_editor_slot_lin_angle": 0.0,
  844. "excellon_editor_slot_circ_dir": 'CW',
  845. "excellon_editor_slot_circ_angle": 0.0,
  846. # Geometry General
  847. "geometry_plot": True,
  848. "geometry_circle_steps": 128,
  849. "geometry_cnctooldia": "0.0944882",
  850. # Geometry Options
  851. "geometry_cutz": -0.0944882,
  852. "geometry_vtipdia": 0.1,
  853. "geometry_vtipangle": 30,
  854. "geometry_multidepth": False,
  855. "geometry_depthperpass": 0.0314961,
  856. "geometry_travelz": 0.0787402,
  857. "geometry_toolchange": False,
  858. "geometry_toolchangez": 0.5,
  859. "geometry_endz": 0.5,
  860. "geometry_feedrate": 3.14961,
  861. "geometry_feedrate_z": 3.14961,
  862. "geometry_spindlespeed": None,
  863. "geometry_dwell": False,
  864. "geometry_dwelltime": 1,
  865. "geometry_ppname_g": 'default',
  866. # Geometry Advanced Options
  867. "geometry_toolchangexy": "0.0, 0.0",
  868. "geometry_startz": None,
  869. "geometry_feedrate_rapid": 3.14961,
  870. "geometry_extracut": False,
  871. "geometry_z_pdepth": -0.02,
  872. "geometry_f_plunge": False,
  873. "geometry_spindledir": 'CW',
  874. "geometry_feedrate_probe": 3.14961,
  875. "geometry_segx": 0.0,
  876. "geometry_segy": 0.0,
  877. # Geometry Editor
  878. "geometry_editor_sel_limit": 30,
  879. # CNC Job General
  880. "cncjob_plot": True,
  881. "cncjob_plot_kind": 'all',
  882. "cncjob_annotation": True,
  883. "cncjob_tooldia": 0.0393701,
  884. "cncjob_coords_type": "G90",
  885. "cncjob_coords_decimals": 4,
  886. "cncjob_fr_decimals": 2,
  887. "cncjob_steps_per_circle": 128,
  888. # CNC Job Options
  889. "cncjob_prepend": "",
  890. "cncjob_append": "",
  891. # CNC Job Advanced Options
  892. "cncjob_toolchange_macro": "",
  893. "cncjob_toolchange_macro_enable": False,
  894. "cncjob_annotation_fontsize": 9,
  895. "cncjob_annotation_fontcolor": '#990000',
  896. # NCC Tool
  897. "tools_ncctools": "0.0393701, 0.019685",
  898. "tools_nccorder": 'rev',
  899. "tools_nccoverlap": 0.015748,
  900. "tools_nccmargin": 0.0393701,
  901. "tools_nccmethod": "seed",
  902. "tools_nccconnect": True,
  903. "tools_ncccontour": True,
  904. "tools_nccrest": False,
  905. "tools_ncc_offset_choice": False,
  906. "tools_ncc_offset_value": 0.0000,
  907. "tools_nccref": 'itself',
  908. "tools_ncc_plotting": 'normal',
  909. "tools_nccmilling_type": 'cl',
  910. "tools_ncctool_type": 'V',
  911. "tools_ncccutz": -0.001968504,
  912. "tools_ncctipdia": 0.00393701,
  913. "tools_ncctipangle": 30,
  914. # Cutout Tool
  915. "tools_cutouttooldia": 0.0944882,
  916. "tools_cutoutkind": "single",
  917. "tools_cutoutmargin": 0.00393701,
  918. "tools_cutoutgapsize": 0.15748,
  919. "tools_gaps_ff": "4",
  920. "tools_cutout_convexshape": False,
  921. # Paint Tool
  922. "tools_painttooldia": 0.023622,
  923. "tools_paintorder": 'rev',
  924. "tools_paintoverlap": 0.015748,
  925. "tools_paintmargin": 0.0,
  926. "tools_paintmethod": "seed",
  927. "tools_selectmethod": "single",
  928. "tools_pathconnect": True,
  929. "tools_paintcontour": True,
  930. "tools_paint_plotting": 'normal',
  931. # 2-Sided Tool
  932. "tools_2sided_mirror_axis": "X",
  933. "tools_2sided_axis_loc": "point",
  934. "tools_2sided_drilldia": 0.0393701,
  935. # Film Tool
  936. "tools_film_type": 'neg',
  937. "tools_film_boundary": 0.0393701,
  938. "tools_film_scale": 0,
  939. "tools_film_color": '#000000',
  940. # Panel Tool
  941. "tools_panelize_spacing_columns": 0,
  942. "tools_panelize_spacing_rows": 0,
  943. "tools_panelize_columns": 1,
  944. "tools_panelize_rows": 1,
  945. "tools_panelize_constrain": False,
  946. "tools_panelize_constrainx": 0.0,
  947. "tools_panelize_constrainy": 0.0,
  948. "tools_panelize_panel_type": 'gerber',
  949. # Calculators Tool
  950. "tools_calc_vshape_tip_dia": 0.007874,
  951. "tools_calc_vshape_tip_angle": 30,
  952. "tools_calc_vshape_cut_z": 0.000787,
  953. "tools_calc_electro_length": 10.0,
  954. "tools_calc_electro_width": 10.0,
  955. "tools_calc_electro_cdensity": 13.0,
  956. "tools_calc_electro_growth": 10.0,
  957. # Transform Tool
  958. "tools_transform_rotate": 90,
  959. "tools_transform_skew_x": 0.0,
  960. "tools_transform_skew_y": 0.0,
  961. "tools_transform_scale_x": 1.0,
  962. "tools_transform_scale_y": 1.0,
  963. "tools_transform_scale_link": True,
  964. "tools_transform_scale_reference": True,
  965. "tools_transform_offset_x": 0.0,
  966. "tools_transform_offset_y": 0.0,
  967. "tools_transform_mirror_reference": False,
  968. "tools_transform_mirror_point": (0, 0),
  969. # SolderPaste Tool
  970. "tools_solderpaste_tools": "0.0393701, 0.011811",
  971. "tools_solderpaste_new": 0.011811,
  972. "tools_solderpaste_z_start": 0.00019685039,
  973. "tools_solderpaste_z_dispense": 0.00393701,
  974. "tools_solderpaste_z_stop": 0.00019685039,
  975. "tools_solderpaste_z_travel": 0.00393701,
  976. "tools_solderpaste_z_toolchange": 0.0393701,
  977. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  978. "tools_solderpaste_frxy": 3.0,
  979. "tools_solderpaste_frz": 3.0,
  980. "tools_solderpaste_frz_dispense": 0.0393701,
  981. "tools_solderpaste_speedfwd": 20,
  982. "tools_solderpaste_dwellfwd": 1,
  983. "tools_solderpaste_speedrev": 10,
  984. "tools_solderpaste_dwellrev": 1,
  985. "tools_solderpaste_pp": 'Paste_1',
  986. # Subtract Tool
  987. "tools_sub_close_paths": True,
  988. # Utilities
  989. # file associations
  990. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  991. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  992. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  993. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  994. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  995. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  996. # Keyword list
  997. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  998. 'Repetier, Roland_MDX_20, Toolchange_Custom, Toolchange_Probe_MACH3, '
  999. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, axisoffset, box, '
  1000. 'center_x, center_y, columns, combine, connect, contour, default, '
  1001. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1002. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1003. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1004. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1005. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1006. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1007. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1008. ,
  1009. })
  1010. # ############################################################
  1011. # ############### Load defaults from file ####################
  1012. # ############################################################
  1013. if user_defaults:
  1014. self.load_defaults(filename='current_defaults')
  1015. # #############################################################
  1016. # ############## APPLY APP LANGUAGE ###########################
  1017. # #############################################################
  1018. ret_val = fcTranslate.apply_language('strings')
  1019. if ret_val == "no language":
  1020. self.inform.emit('[ERROR] %s' %
  1021. _("Could not find the Language files. The App strings are missing."))
  1022. log.debug("Could not find the Language files. The App strings are missing.")
  1023. else:
  1024. # make the current language the current selection on the language combobox
  1025. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1026. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1027. # ##############################################################
  1028. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1029. # ##############################################################
  1030. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1031. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1032. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1033. self.save_defaults(silent=True)
  1034. self.propagate_defaults(silent=True)
  1035. self.restore_main_win_geom()
  1036. def auto_save_defaults():
  1037. try:
  1038. self.save_defaults(silent=True)
  1039. self.propagate_defaults(silent=True)
  1040. finally:
  1041. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1042. # the following lines activates automatic defaults save
  1043. # if user_defaults:
  1044. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1045. # self.options_form = PreferencesUI()
  1046. self.options_form_fields = {
  1047. "units": self.ui.general_options_form.general_app_group.units_radio,
  1048. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1049. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1050. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1051. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1052. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1053. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1054. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1055. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1056. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1057. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1058. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1059. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1060. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1061. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1062. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1063. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1064. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1065. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1066. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1067. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1068. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1069. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1070. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1071. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1072. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1073. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1074. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1075. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1076. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1077. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1078. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1079. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1080. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1081. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1082. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1083. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1084. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1085. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1086. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1087. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1088. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1089. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1090. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1091. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1092. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1093. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1094. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1095. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1096. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1097. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1098. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1099. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1100. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1101. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1102. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1103. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1104. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1105. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1106. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1107. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1108. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1109. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1110. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1111. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1112. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1113. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1114. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1115. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1116. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1117. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1118. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1119. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1120. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1121. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1122. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1123. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1124. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1125. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1126. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1127. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1128. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1129. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1130. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1131. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1132. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1133. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1134. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1135. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1136. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1137. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1138. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1139. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1140. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1141. }
  1142. for name in list(self.postprocessors.keys()):
  1143. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1144. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1145. self.options = LoudDict()
  1146. self.options.set_change_callback(self.on_options_dict_change)
  1147. self.options.update({
  1148. "units": "IN",
  1149. "global_gridx": 1.0,
  1150. "global_gridy": 1.0,
  1151. "global_snap_max": 0.05,
  1152. "global_background_timeout": 300000, # Default value is 5 minutes
  1153. "global_verbose_error_level": 0, # Shell verbosity:
  1154. # 0 = default(python trace only for unknown errors),
  1155. # 1 = show trace(show trace allways), 2 = (For the future).
  1156. "gerber_plot": True,
  1157. "gerber_solid": True,
  1158. "gerber_multicolored": False,
  1159. "gerber_isotooldia": 0.016,
  1160. "gerber_isopasses": 1,
  1161. "gerber_isooverlap": 0.15,
  1162. "gerber_combine_passes": True,
  1163. "gerber_noncoppermargin": 0.0,
  1164. "gerber_noncopperrounded": False,
  1165. "gerber_bboxmargin": 0.0,
  1166. "gerber_bboxrounded": False,
  1167. "excellon_plot": True,
  1168. "excellon_solid": False,
  1169. "excellon_format_upper_in": 2,
  1170. "excellon_format_lower_in": 4,
  1171. "excellon_format_upper_mm": 3,
  1172. "excellon_format_lower_mm": 3,
  1173. "excellon_units": 'INCH',
  1174. "excellon_optimization_type": 'B',
  1175. "excellon_search_time": 3,
  1176. "excellon_zeros": "L",
  1177. "excellon_drillz": -0.1,
  1178. "excellon_travelz": 0.1,
  1179. "excellon_feedrate": 3.0,
  1180. "excellon_feedrate_rapid": 3.0,
  1181. "excellon_spindlespeed": None,
  1182. "excellon_spindledir": 'CW',
  1183. "excellon_dwell": True,
  1184. "excellon_dwelltime": 1000,
  1185. "excellon_toolchange": False,
  1186. "excellon_toolchangez": 1.0,
  1187. "excellon_toolchangexy": "0.0, 0.0",
  1188. "excellon_tooldia": 0.016,
  1189. "excellon_ppname_e": 'default',
  1190. "excellon_f_plunge": False,
  1191. "excellon_startz": None,
  1192. "excellon_endz": 2.0,
  1193. "geometry_plot": True,
  1194. "geometry_segx": 0.0,
  1195. "geometry_segy": 0.0,
  1196. "geometry_cutz": -0.002,
  1197. "geometry_vtipdia": 0.1,
  1198. "geometry_vtipangle": 30,
  1199. "geometry_travelz": 0.1,
  1200. "geometry_feedrate": 3.0,
  1201. "geometry_feedrate_z": 3.0,
  1202. "geometry_feedrate_rapid": 3.0,
  1203. "geometry_spindlespeed": None,
  1204. "geometry_spindledir": 'CW',
  1205. "geometry_dwell": True,
  1206. "geometry_dwelltime": 1000,
  1207. "geometry_cnctooldia": 0.016,
  1208. "geometry_toolchange": False,
  1209. "geometry_toolchangez": 2.0,
  1210. "geometry_toolchangexy": "0.0, 0.0",
  1211. "geometry_startz": None,
  1212. "geometry_endz": 2.0,
  1213. "geometry_ppname_g": "default",
  1214. "geometry_f_plunge": False,
  1215. "geometry_depthperpass": 0.002,
  1216. "geometry_multidepth": False,
  1217. "geometry_extracut": False,
  1218. "cncjob_plot": True,
  1219. "cncjob_tooldia": 0.016,
  1220. "cncjob_prepend": "",
  1221. "cncjob_append": "",
  1222. "tools_ncctools": "1.0, 0.5",
  1223. "tools_nccoverlap": 0.4,
  1224. "tools_nccmargin": 1,
  1225. "tools_cutouttooldia": 0.07,
  1226. "tools_cutoutmargin": 0.1,
  1227. "tools_cutoutgapsize": 0.15,
  1228. "tools_gaps_ff": "8",
  1229. "tools_painttooldia": 0.07,
  1230. "tools_paintoverlap": 0.15,
  1231. "tools_paintmargin": 0.0,
  1232. "tools_paintmethod": "seed",
  1233. "tools_selectmethod": "single",
  1234. "tools_pathconnect": True,
  1235. "tools_paintcontour": True,
  1236. "tools_2sided_mirror_axis": "X",
  1237. "tools_2sided_axis_loc": 'point',
  1238. "tools_2sided_drilldia": 1,
  1239. "tools_film_type": 'neg',
  1240. "tools_film_boundary": 1,
  1241. "tools_film_scale": 0,
  1242. "tools_panelize_spacing_columns": 0,
  1243. "tools_panelize_spacing_rows": 0,
  1244. "tools_panelize_columns": 1,
  1245. "tools_panelize_rows": 1,
  1246. "tools_panelize_constrain": False,
  1247. "tools_panelize_constrainx": 0.0,
  1248. "tools_panelize_constrainy": 0.0
  1249. })
  1250. self.options.update(self.defaults) # Copy app defaults to project options
  1251. self.gen_form = None
  1252. self.ger_form = None
  1253. self.exc_form = None
  1254. self.geo_form = None
  1255. self.cnc_form = None
  1256. self.tools_form = None
  1257. self.fa_form = None
  1258. self.on_options_combo_change(0) # Will show the initial form
  1259. # ################################
  1260. # ### Initialize the color box's color in Preferences -> Global -> Color
  1261. # Init Plot Colors
  1262. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1263. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1264. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1265. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1266. int(self.defaults['global_plot_fill'][7:9], 16))
  1267. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1268. int(self.defaults['global_plot_fill'][7:9], 16))
  1269. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1270. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1271. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1272. # Init Left-Right Selection colors
  1273. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1274. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1275. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1276. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1277. int(self.defaults['global_sel_fill'][7:9], 16))
  1278. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1279. int(self.defaults['global_sel_fill'][7:9], 16))
  1280. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1281. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1282. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1283. # Init Right-Left Selection colors
  1284. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1285. self.defaults['global_alt_sel_fill'])
  1286. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1287. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1288. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1289. int(self.defaults['global_sel_fill'][7:9], 16))
  1290. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1291. int(self.defaults['global_sel_fill'][7:9], 16))
  1292. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1293. self.defaults['global_alt_sel_line'])
  1294. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1295. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1296. # Init Draw color and Selection Draw Color
  1297. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1298. self.defaults['global_draw_color'])
  1299. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1300. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1301. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1302. self.defaults['global_sel_draw_color'])
  1303. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1304. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1305. # Init Project Items color
  1306. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1307. self.defaults['global_proj_item_color'])
  1308. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1309. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1310. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1311. self.defaults['global_proj_item_dis_color'])
  1312. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1313. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1314. # Init the Annotation CNC Job color
  1315. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1316. self.defaults['cncjob_annotation_fontcolor'])
  1317. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1318. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1319. # Init the Tool Film color
  1320. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1321. self.defaults['tools_film_color'])
  1322. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1323. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1324. # ### End of Data ####
  1325. # ###############################################
  1326. # ############# SETUP Plot Area #################
  1327. # ###############################################
  1328. if show_splash:
  1329. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1330. "Canvas initialization started."),
  1331. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1332. color=QtGui.QColor("gray"))
  1333. start_plot_time = time.time() # debug
  1334. self.plotcanvas = None
  1335. self.app_cursor = None
  1336. self.hover_shapes = None
  1337. self.on_plotcanvas_setup()
  1338. end_plot_time = time.time()
  1339. self.used_time = end_plot_time - start_plot_time
  1340. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1341. if show_splash:
  1342. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1343. "Canvas initialization started.\n"
  1344. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1345. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1346. color=QtGui.QColor("gray"))
  1347. self.ui.splitter.setStretchFactor(1, 2)
  1348. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1349. # depending on from where those tools are called different actions can be done
  1350. self.call_source = 'app'
  1351. # ##############################################
  1352. # ######### SETUP OBJECT COLLECTION ############
  1353. # ##############################################
  1354. self.collection = ObjectCollection(self)
  1355. self.ui.project_tab_layout.addWidget(self.collection.view)
  1356. # ### Adjust tabs width ## ##
  1357. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1358. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1359. self.collection.view.setMinimumWidth(290)
  1360. self.log.debug("Finished creating Object Collection.")
  1361. # ###############################################
  1362. # ############# Worker SETUP ####################
  1363. # ###############################################
  1364. if self.defaults["global_worker_number"]:
  1365. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1366. else:
  1367. self.workers = WorkerStack(workers_number=2)
  1368. self.worker_task.connect(self.workers.add_task)
  1369. self.log.debug("Finished creating Workers crew.")
  1370. # ################################################
  1371. # ############### Signal handling ################
  1372. # ################################################
  1373. # ############# Custom signals ##################
  1374. # signal for displaying messages in status bar
  1375. self.inform.connect(self.info)
  1376. # signal to be called when the app is quiting
  1377. self.app_quit.connect(self.quit_application)
  1378. self.message.connect(self.message_dialog)
  1379. self.progress.connect(self.set_progress_bar)
  1380. # signals that are emitted when object state changes
  1381. self.object_created.connect(self.on_object_created)
  1382. self.object_changed.connect(self.on_object_changed)
  1383. self.object_plotted.connect(self.on_object_plotted)
  1384. self.plots_updated.connect(self.on_plots_updated)
  1385. # signals emitted when file state change
  1386. self.file_opened.connect(self.register_recent)
  1387. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1388. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1389. # ############# Standard signals ###################
  1390. # ### Menu
  1391. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1392. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1393. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1394. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1395. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1396. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1397. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1398. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1399. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1400. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1401. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1402. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1403. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1404. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1405. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1406. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1407. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1408. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1409. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1410. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1411. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1412. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1413. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1414. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1415. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1416. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1417. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1418. self.ui.menufile_exit.triggered.connect(self.final_save)
  1419. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1420. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1421. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1422. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1423. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1424. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1425. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1426. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1427. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1428. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1429. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1430. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1431. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1432. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1433. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1434. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1435. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1436. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1437. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1438. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1439. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1440. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1441. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1442. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1443. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1444. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1445. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1446. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1447. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1448. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1449. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1450. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1451. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1452. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1453. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1454. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1455. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1456. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1457. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1458. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1459. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1460. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1461. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1462. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1463. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1464. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1465. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1466. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1467. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1468. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1469. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1470. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1471. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1472. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1473. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1474. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1475. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1476. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1477. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1478. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1479. # ToolBar signals
  1480. self.connect_toolbar_signals()
  1481. # Notebook signals
  1482. # make the right click on the notebook tab connect to a function
  1483. self.ui.notebook.setupContextMenu()
  1484. self.ui.notebook.addContextMenu(
  1485. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1486. initial_checked=self.defaults["global_tabs_detachable"])
  1487. # activate initial state
  1488. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1489. # Context Menu
  1490. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1491. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1492. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1493. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1494. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1495. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1496. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1497. self.ui.clearplot.triggered.connect(self.clear_plots)
  1498. self.ui.replot.triggered.connect(self.plot_all)
  1499. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1500. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1501. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1502. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1503. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1504. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1505. # Preferences Plot Area TAB
  1506. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1507. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1508. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1509. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1510. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1511. # ##############################
  1512. # ### GUI PREFERENCES SIGNALS ##
  1513. # ##############################
  1514. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1515. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1516. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1517. )
  1518. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1519. lambda: self.on_toggle_units(no_pref=False))
  1520. # ###############################################################
  1521. # ################### GUI COLORS SIGNALS ########################
  1522. # ###############################################################
  1523. # Setting plot colors signals
  1524. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1525. self.on_pf_color_entry)
  1526. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1527. self.on_pf_color_button)
  1528. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1529. self.on_pf_color_spinner)
  1530. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1531. self.on_pf_color_slider)
  1532. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1533. self.on_pl_color_entry)
  1534. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1535. self.on_pl_color_button)
  1536. # Setting selection (left - right) colors signals
  1537. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1538. self.on_sf_color_entry)
  1539. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1540. self.on_sf_color_button)
  1541. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1542. self.on_sf_color_spinner)
  1543. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1544. self.on_sf_color_slider)
  1545. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1546. self.on_sl_color_entry)
  1547. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1548. self.on_sl_color_button)
  1549. # Setting selection (right - left) colors signals
  1550. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1551. self.on_alt_sf_color_entry)
  1552. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1553. self.on_alt_sf_color_button)
  1554. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1555. self.on_alt_sf_color_spinner)
  1556. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1557. self.on_alt_sf_color_slider)
  1558. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1559. self.on_alt_sl_color_entry)
  1560. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1561. self.on_alt_sl_color_button)
  1562. # Setting Editor Draw colors signals
  1563. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1564. self.on_draw_color_entry)
  1565. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1566. self.on_draw_color_button)
  1567. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1568. self.on_sel_draw_color_entry)
  1569. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1570. self.on_sel_draw_color_button)
  1571. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1572. self.on_proj_color_entry)
  1573. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1574. self.on_proj_color_button)
  1575. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1576. self.on_proj_color_dis_entry)
  1577. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1578. self.on_proj_color_dis_button)
  1579. # ########## workspace setting signals ###########
  1580. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1581. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1582. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1583. # ########## CNC Job related signals #############
  1584. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1585. self.on_cnc_custom_parameters)
  1586. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1587. self.on_annotation_fontcolor_entry)
  1588. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1589. self.on_annotation_fontcolor_button)
  1590. # ########## Tools related signals #############
  1591. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1592. self.on_film_color_entry)
  1593. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1594. self.on_film_color_button)
  1595. # ########## Modify G-CODE Plot Area TAB ###########
  1596. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1597. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1598. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1599. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1600. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1601. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1602. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1603. # portability changed signal
  1604. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1605. # Object list
  1606. self.collection.view.activated.connect(self.on_row_activated)
  1607. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1608. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1609. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1610. # Export Excellon parameters.
  1611. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1612. self.on_update_exc_export
  1613. )
  1614. # call it once to make sure it is updated at startup
  1615. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1616. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1617. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1618. self.on_excellon_defaults_button)
  1619. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1620. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1621. self.on_excellon_options_button)
  1622. # when there are arguments at application startup this get launched
  1623. self.args_at_startup[list].connect(self.on_startup_args)
  1624. # ##############################################################
  1625. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1626. # ##############################################################
  1627. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1628. lambda: self.restore_extensions(ext_type='excellon'))
  1629. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1630. lambda: self.restore_extensions(ext_type='gcode'))
  1631. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1632. lambda: self.restore_extensions(ext_type='gerber'))
  1633. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1634. lambda: self.delete_all_extensions(ext_type='excellon'))
  1635. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1636. lambda: self.delete_all_extensions(ext_type='gcode'))
  1637. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1638. lambda: self.delete_all_extensions(ext_type='gerber'))
  1639. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1640. lambda: self.add_extension(ext_type='excellon'))
  1641. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1642. lambda: self.add_extension(ext_type='gcode'))
  1643. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1644. lambda: self.add_extension(ext_type='gerber'))
  1645. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1646. lambda: self.del_extension(ext_type='excellon'))
  1647. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1648. lambda: self.del_extension(ext_type='gcode'))
  1649. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1650. lambda: self.del_extension(ext_type='gerber'))
  1651. # connect the 'Apply' buttons from the Preferences/File Associations
  1652. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1653. lambda: self.on_register_files(obj_type='excellon'))
  1654. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1655. lambda: self.on_register_files(obj_type='gcode'))
  1656. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1657. lambda: self.on_register_files(obj_type='gerber'))
  1658. # ##############################################################
  1659. # ###################### KEYWORDS SIGNALS ######################
  1660. # ##############################################################
  1661. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1662. lambda: self.restore_extensions(ext_type='keyword'))
  1663. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1664. lambda: self.delete_all_extensions(ext_type='keyword'))
  1665. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1666. lambda: self.add_extension(ext_type='keyword'))
  1667. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1668. lambda: self.del_extension(ext_type='keyword'))
  1669. # splash screen button signal
  1670. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1671. # connect the abort_all_tasks related slots to the related signals
  1672. self.proc_container.idle_flag.connect(self.app_is_idle)
  1673. # #####################################################################################
  1674. # ########### FINISHED CONNECTING SIGNALS #############################################
  1675. # #####################################################################################
  1676. self.log.debug("Finished connecting Signals.")
  1677. # #####################################################################################
  1678. # ########################## Other setups #############################################
  1679. # #####################################################################################
  1680. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1681. self.tool_tab_locked = False
  1682. # decide if to show or hide the Notebook side of the screen at startup
  1683. if self.defaults["global_project_at_startup"] is True:
  1684. self.ui.splitter.setSizes([1, 1])
  1685. else:
  1686. self.ui.splitter.setSizes([0, 1])
  1687. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1688. self.setup_obj_classes()
  1689. self.setup_recent_items()
  1690. self.setup_component_editor()
  1691. # #####################################################################################
  1692. # ######################### Auto-complete KEYWORDS ####################################
  1693. # #####################################################################################
  1694. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1695. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1696. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1697. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1698. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1699. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1700. 'mirror', 'ncc',
  1701. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1702. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1703. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'save', 'save_project',
  1704. 'save_sys', 'scale',
  1705. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1706. 'version', 'write_gcode'
  1707. ]
  1708. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1709. 'Repetier', 'Roland_MDX_20', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1710. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset',
  1711. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1712. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1713. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1714. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1715. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1716. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1717. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1718. 'spacing_columns',
  1719. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1720. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1721. ]
  1722. self.tcl_keywords = [
  1723. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1724. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1725. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1726. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1727. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1728. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1729. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1730. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1731. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1732. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1733. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1734. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1735. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1736. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1737. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1738. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1739. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1740. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1741. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1742. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1743. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1744. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1745. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1746. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1747. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1748. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1749. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1750. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1751. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1752. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1753. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1754. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1755. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1756. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1757. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1758. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1759. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1760. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1761. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1762. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1763. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1764. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1765. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1766. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1767. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1768. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1769. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1770. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1771. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1772. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1773. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1774. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1775. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1776. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1777. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1778. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1779. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1780. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1781. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1782. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1783. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1784. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1785. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1786. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1787. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1788. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1789. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1790. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1791. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1792. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1793. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1794. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1795. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1796. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1797. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1798. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1799. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1800. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1801. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1802. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1803. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1804. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1805. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1806. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1807. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1808. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1809. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1810. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1811. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1812. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1813. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1814. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1815. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1816. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1817. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1818. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1819. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1820. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1821. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1822. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1823. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1824. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1825. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1826. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1827. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1828. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1829. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1830. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1831. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1832. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1833. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1834. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1835. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1836. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1837. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1838. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1839. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1840. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1841. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1842. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1843. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1844. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1845. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1846. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1847. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1848. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1849. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1850. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1851. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1852. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1853. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1854. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1855. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1856. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1857. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1858. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1859. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1860. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1861. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1862. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1863. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1864. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1865. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1866. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1867. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1868. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1869. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1870. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1871. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1872. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1873. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1874. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1875. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1876. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1877. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1878. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1879. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1880. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1881. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1882. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1883. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1884. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1885. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1886. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1887. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1888. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1889. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1890. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1891. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1892. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1893. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1894. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1895. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1896. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1897. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1898. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1899. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1900. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1901. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1902. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1903. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1904. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1905. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1906. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1907. ]
  1908. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1909. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1910. self.default_autocomplete_keywords = [
  1911. 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  1912. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  1913. 'drilled_dias', 'drillz', 'pp',
  1914. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1915. 'milled_dias',
  1916. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1917. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1918. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1919. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move',
  1920. 'default', 'feedrate_z', 'grbl_11', 'grbl_laser', 'hpgl', 'line_xyz', 'marlin',
  1921. 'Paste_1', 'Repetier', 'Toolchange_Custom', 'Roland_MDX_20', 'Toolchange_manual',
  1922. 'Toolchange_Probe_MACH3', 'dwell', 'dwelltime', 'toolchange_xy', 'iso_type',
  1923. 'Desktop', 'FlatPrj', 'FlatConfig', 'Users', 'Documents', 'My Documents', 'Marius'
  1924. ]
  1925. # ####################################################################################
  1926. # ####################### Shell SETUP ################################################
  1927. # ####################################################################################
  1928. self.shell = FCShell(self, version=self.version)
  1929. self.shell._edit.set_model_data(self.myKeywords)
  1930. self.ui.code_editor.set_model_data(self.myKeywords)
  1931. self.shell.setWindowIcon(self.ui.app_icon)
  1932. self.shell.setWindowTitle("FlatCAM Shell")
  1933. self.shell.resize(*self.defaults["global_shell_shape"])
  1934. self.shell.append_output("FlatCAM %s - " % self.version)
  1935. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1936. self.init_tcl()
  1937. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1938. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1939. self.ui.shell_dock.setWidget(self.shell)
  1940. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1941. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1942. QtWidgets.QDockWidget.DockWidgetFloatable |
  1943. QtWidgets.QDockWidget.DockWidgetClosable)
  1944. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1945. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1946. if self.defaults["global_shell_at_startup"]:
  1947. self.ui.shell_dock.show()
  1948. else:
  1949. self.ui.shell_dock.hide()
  1950. # ##################################################################################
  1951. # ###################### Tools and Plugins #########################################
  1952. # ##################################################################################
  1953. self.dblsidedtool = None
  1954. self.measurement_tool = None
  1955. self.panelize_tool = None
  1956. self.film_tool = None
  1957. self.paste_tool = None
  1958. self.calculator_tool = None
  1959. self.sub_tool = None
  1960. self.move_tool = None
  1961. self.cutout_tool = None
  1962. self.ncclear_tool = None
  1963. self.paint_tool = None
  1964. self.transform_tool = None
  1965. self.properties_tool = None
  1966. self.pdf_tool = None
  1967. self.image_tool = None
  1968. self.pcb_wizard_tool = None
  1969. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1970. self.install_tools()
  1971. # ### System Font Parsing ###
  1972. # self.f_parse = ParseFont(self)
  1973. # self.parse_system_fonts()
  1974. # #####################################################################################
  1975. # ######################## Check for updates ##########################################
  1976. # #####################################################################################
  1977. # Separate thread (Not worker)
  1978. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1979. if (self.beta is False or self.beta is None) and \
  1980. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1981. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1982. self.thr2 = QtCore.QThread()
  1983. self.worker_task.emit({'fcn': self.version_check,
  1984. 'params': []})
  1985. self.thr2.start(QtCore.QThread.LowPriority)
  1986. # #####################################################################################
  1987. # ###################### Variables for global usage ###################################
  1988. # #####################################################################################
  1989. # register files with FlatCAM; it works only for Windows for now
  1990. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1991. self.on_register_files()
  1992. # coordinates for relative position display
  1993. self.rel_point1 = (0, 0)
  1994. self.rel_point2 = (0, 0)
  1995. # variable to store coordinates
  1996. self.pos = (0, 0)
  1997. self.pos_jump = (0, 0)
  1998. # variable to store mouse coordinates
  1999. self.mouse = [0, 0]
  2000. # decide if we have a double click or single click
  2001. self.doubleclick = False
  2002. # variable to store if a command is active (then the var is not None) and which one it is
  2003. self.command_active = None
  2004. # variable to store the status of moving selection action
  2005. # None value means that it's not an selection action
  2006. # True value = a selection from left to right
  2007. # False value = a selection from right to left
  2008. self.selection_type = None
  2009. # List to store the objects that are currently loaded in FlatCAM
  2010. # This list is updated on each object creation or object delete
  2011. self.all_objects_list = list()
  2012. # List to store the objects that are selected
  2013. self.sel_objects_list = list()
  2014. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2015. self.key_modifiers = None
  2016. # Variable to hold the status of the axis
  2017. self.toggle_axis = True
  2018. # Variable to store the status of the fullscreen event
  2019. self.toggle_fscreen = False
  2020. # Variable to store the status of the code editor
  2021. self.toggle_codeeditor = False
  2022. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2023. self.click_noproject = False
  2024. self.cursor = None
  2025. # Variable to store the GCODE that was edited
  2026. self.gcode_edited = ""
  2027. # reference for the self.ui.code_editor
  2028. self.reference_code_editor = None
  2029. self.script_code = ''
  2030. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2031. self.preferences_changed_flag = False
  2032. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2033. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2034. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2035. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2036. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2037. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2038. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2039. 'tap', 'xpi']
  2040. self.svg_list = ['svg']
  2041. self.dxf_list = ['dxf']
  2042. self.pdf_list = ['pdf']
  2043. self.prj_list = ['flatprj']
  2044. self.conf_list = ['flatconfig']
  2045. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2046. # flag for polygons not cleared
  2047. self.poly_not_cleared = False
  2048. # VisPy visuals
  2049. self.isHovering = False
  2050. self.notHovering = True
  2051. # when True, the app has to return from any thread
  2052. self.abort_flag = False
  2053. # ###############################################################################
  2054. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2055. # ############# It's done only once after install ###############
  2056. # ###############################################################################
  2057. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2058. fac_def_from_file = factory_file.read()
  2059. factory_defaults = json.loads(fac_def_from_file)
  2060. # if the file contain an empty dictionary then save the factory defaults into the file
  2061. if not factory_defaults:
  2062. self.save_factory_defaults(silent=False)
  2063. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2064. initial_lay = 'compact'
  2065. self.on_layout(lay=initial_lay)
  2066. # Set the combobox in Preferences to the current layout
  2067. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2068. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2069. factory_file.close()
  2070. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2071. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2072. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2073. # after the first run, this object should be False
  2074. self.defaults["first_run"] = False
  2075. # ###############################################################################
  2076. # ################# ADDING FlatCAM EDITORS section ##############################
  2077. # ###############################################################################
  2078. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2079. # at the first launch of the App , the editors will not be functional.
  2080. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2081. self.exc_editor = FlatCAMExcEditor(self)
  2082. self.grb_editor = FlatCAMGrbEditor(self)
  2083. self.log.debug("Finished adding FlatCAM Editor's.")
  2084. self.set_ui_title(name=_("New Project - Not saved"))
  2085. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2086. current_platform = platform.architecture()[0]
  2087. if current_platform != '64bit':
  2088. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2089. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2090. # ###############################################################################
  2091. # ####################### Finished the CONSTRUCTOR ##############################
  2092. # ###############################################################################
  2093. App.log.debug("END of constructor. Releasing control.")
  2094. # #####################################################################################
  2095. # ########################## SHOW GUI #################################################
  2096. # #####################################################################################
  2097. # finish the splash
  2098. self.splash.finish(self.ui)
  2099. settings = QSettings("Open Source", "FlatCAM")
  2100. if settings.contains("maximized_gui"):
  2101. maximized_ui = settings.value('maximized_gui', type=bool)
  2102. if maximized_ui is True:
  2103. self.ui.showMaximized()
  2104. else:
  2105. self.ui.show()
  2106. else:
  2107. self.ui.show()
  2108. self.trayIcon.show()
  2109. # #####################################################################################
  2110. # ########################## START-UP ARGUMENTS #######################################
  2111. # #####################################################################################
  2112. # test if the program was started with a script as parameter
  2113. if self.cmd_line_shellvar:
  2114. try:
  2115. cnt = 0
  2116. command_tcl = 0
  2117. for i in self.cmd_line_shellvar.split(','):
  2118. if i is not None:
  2119. try:
  2120. command_tcl = eval(i)
  2121. except:
  2122. command_tcl = i
  2123. command_tcl_formatted = 'set shellvar_{nr} {cmd}'.format(cmd=str(command_tcl), nr=str(cnt))
  2124. cnt += 1
  2125. # if there are Windows paths then replace the path separator with a Unix like one
  2126. if sys.platform == 'win32':
  2127. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2128. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2129. except Exception as ext:
  2130. print("ERROR: ", ext)
  2131. sys.exit(2)
  2132. if self.cmd_line_shellfile:
  2133. try:
  2134. if self.ui.shell_dock.isHidden():
  2135. self.ui.shell_dock.show()
  2136. with open(self.cmd_line_shellfile, "r") as myfile:
  2137. if show_splash:
  2138. self.splash.showMessage('%s: %ssec\n%s' % (
  2139. _("Canvas initialization started.\n"
  2140. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2141. _("Executing Tcl Script ...")),
  2142. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2143. color=QtGui.QColor("gray"))
  2144. cmd_line_shellfile_text = myfile.read()
  2145. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2146. except Exception as ext:
  2147. print("ERROR: ", ext)
  2148. sys.exit(2)
  2149. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2150. # the path/file_name must be enclosed in quotes if it contain spaces
  2151. if App.args:
  2152. self.args_at_startup.emit(App.args)
  2153. @staticmethod
  2154. def copy_and_overwrite(from_path, to_path):
  2155. """
  2156. From here:
  2157. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2158. :param from_path: source path
  2159. :param to_path: destination path
  2160. :return: None
  2161. """
  2162. if os.path.exists(to_path):
  2163. shutil.rmtree(to_path)
  2164. try:
  2165. shutil.copytree(from_path, to_path)
  2166. except FileNotFoundError:
  2167. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2168. shutil.copytree(from_new_path, to_path)
  2169. def on_startup_args(self, args):
  2170. """
  2171. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2172. :param args: a list containing the application args at startup
  2173. :return: None
  2174. """
  2175. if args is not None:
  2176. args_to_process = args
  2177. else:
  2178. args_to_process = App.args
  2179. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2180. for argument in args_to_process:
  2181. if '.FlatPrj' in argument:
  2182. try:
  2183. project_name = str(argument)
  2184. if project_name == "":
  2185. self.inform.emit(_("Open cancelled."))
  2186. else:
  2187. # self.open_project(project_name)
  2188. run_from_arg = True
  2189. # self.worker_task.emit({'fcn': self.open_project,
  2190. # 'params': [project_name, run_from_arg]})
  2191. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2192. except Exception as e:
  2193. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2194. elif '.FlatConfig' in argument:
  2195. try:
  2196. file_name = str(argument)
  2197. if file_name == "":
  2198. self.inform.emit(_("Open Config file failed."))
  2199. else:
  2200. run_from_arg = True
  2201. # self.worker_task.emit({'fcn': self.open_config_file,
  2202. # 'params': [file_name, run_from_arg]})
  2203. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2204. except Exception as e:
  2205. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2206. elif '.FlatScript' in argument:
  2207. try:
  2208. file_name = str(argument)
  2209. if file_name == "":
  2210. self.inform.emit(_("Open Script file failed."))
  2211. else:
  2212. # run_from_arg = True
  2213. # self.worker_task.emit({'fcn': self.open_script_file,
  2214. # 'params': [file_name, run_from_arg]})
  2215. self.on_filerunscript(name=file_name)
  2216. except Exception as e:
  2217. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2218. elif 'quit' in argument or 'exit' in argument:
  2219. log.debug("App.on_startup_args() --> Quit event.")
  2220. sys.exit()
  2221. elif 'save' in argument:
  2222. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2223. self.save_defaults()
  2224. else:
  2225. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2226. proc_arg = argument.lower()
  2227. for ext in exc_list:
  2228. proc_ext = ext.replace(' ', '')
  2229. proc_ext = '.%s' % proc_ext
  2230. if proc_ext.lower() in proc_arg and proc_ext != '':
  2231. file_name = str(argument)
  2232. if file_name == "":
  2233. self.inform.emit(_("Open Excellon file failed."))
  2234. else:
  2235. self.on_fileopenexcellon(name=file_name)
  2236. return
  2237. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2238. for ext in gco_list:
  2239. proc_ext = ext.replace(' ', '')
  2240. proc_ext = '.%s' % proc_ext
  2241. if proc_ext.lower() in proc_arg and proc_ext != '':
  2242. print(proc_ext, proc_arg)
  2243. file_name = str(argument)
  2244. if file_name == "":
  2245. self.inform.emit(_("Open GCode file failed."))
  2246. else:
  2247. self.on_fileopengcode(name=file_name)
  2248. return
  2249. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2250. for ext in grb_list:
  2251. proc_ext = ext.replace(' ', '')
  2252. proc_ext = '.%s' % proc_ext
  2253. if proc_ext.lower() in proc_arg and proc_ext != '':
  2254. file_name = str(argument)
  2255. if file_name == "":
  2256. self.inform.emit(_("Open Gerber file failed."))
  2257. else:
  2258. self.on_fileopengerber(name=file_name)
  2259. return
  2260. def set_ui_title(self, name):
  2261. """
  2262. Sets the title of the main window.
  2263. :param name: String that store the project path and project name
  2264. :return: None
  2265. """
  2266. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2267. (self.version,
  2268. ('BETA' if self.beta else ''),
  2269. platform.architecture()[0],
  2270. name)
  2271. )
  2272. def defaults_read_form(self):
  2273. """
  2274. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2275. :return: None
  2276. """
  2277. for option in self.defaults_form_fields:
  2278. try:
  2279. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2280. except Exception as e:
  2281. log.debug("App.defaults_read_form() --> %s" % str(e))
  2282. def defaults_write_form(self, factor=None, fl_units=None):
  2283. """
  2284. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2285. self.defaults dictionary.
  2286. :param factor: will apply a factor to the values that written in the GUI elements
  2287. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2288. :return: None
  2289. """
  2290. for option in self.defaults:
  2291. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2292. # try:
  2293. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2294. # except KeyError:
  2295. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2296. # # TODO: Rethink this?
  2297. # pass
  2298. def defaults_write_form_field(self, field, factor=None, units=None):
  2299. """
  2300. Basically it is the worker in the self.defaults_write_form()
  2301. :param field: the GUI element in Preferences GUI to be updated
  2302. :param factor: factor to be applied to the field parameter
  2303. :param units: current FLatCAM measuring units
  2304. :return: None, it updates GUI elements
  2305. """
  2306. try:
  2307. if factor is None:
  2308. if units is None:
  2309. self.defaults_form_fields[field].set_value(self.defaults[field])
  2310. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2311. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2312. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2313. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2314. else:
  2315. if units is None:
  2316. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2317. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2318. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2319. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2320. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2321. except KeyError:
  2322. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2323. # TODO: Rethink this?
  2324. pass
  2325. except AttributeError:
  2326. log.debug(field)
  2327. def clear_pool(self):
  2328. """
  2329. Clear the multiprocessing pool and calls garbage collector.
  2330. :return: None
  2331. """
  2332. self.pool.close()
  2333. self.pool = Pool()
  2334. self.pool_recreated.emit(self.pool)
  2335. gc.collect()
  2336. def install_tools(self):
  2337. """
  2338. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2339. Instantiation of the Tools classes.
  2340. The order that the tools are installed is important as they can depend on each other install position.
  2341. :return: None
  2342. """
  2343. self.dblsidedtool = DblSidedTool(self)
  2344. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2345. self.measurement_tool = Measurement(self)
  2346. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2347. self.panelize_tool = Panelize(self)
  2348. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2349. self.film_tool = Film(self)
  2350. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2351. self.paste_tool = SolderPaste(self)
  2352. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2353. self.calculator_tool = ToolCalculator(self)
  2354. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2355. self.sub_tool = ToolSub(self)
  2356. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2357. self.move_tool = ToolMove(self)
  2358. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2359. before=self.ui.menueditorigin)
  2360. self.cutout_tool = CutOut(self)
  2361. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2362. before=self.measurement_tool.menuAction)
  2363. self.ncclear_tool = NonCopperClear(self)
  2364. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2365. before=self.measurement_tool.menuAction, separator=True)
  2366. self.paint_tool = ToolPaint(self)
  2367. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2368. before=self.measurement_tool.menuAction, separator=True)
  2369. self.transform_tool = ToolTransform(self)
  2370. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2371. self.properties_tool = Properties(self)
  2372. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2373. self.pdf_tool = ToolPDF(self)
  2374. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2375. separator=True)
  2376. self.image_tool = ToolImage(self)
  2377. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2378. separator=True)
  2379. self.pcb_wizard_tool = PcbWizard(self)
  2380. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2381. self.log.debug("Tools are installed.")
  2382. def remove_tools(self):
  2383. """
  2384. Will remove all the actions in the Tool menu.
  2385. :return: None
  2386. """
  2387. for act in self.ui.menutool.actions():
  2388. self.ui.menutool.removeAction(act)
  2389. def init_tools(self):
  2390. """
  2391. Initialize the Tool tab in the notebook side of the central widget.
  2392. Remove the actions in the Tools menu.
  2393. Instantiate again the FlatCAM tools (plugins).
  2394. All this is required when changing the layout: standard, compact etc.
  2395. :return: None
  2396. """
  2397. log.debug("init_tools()")
  2398. # delete the data currently in the Tools Tab and the Tab itself
  2399. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2400. if widget is not None:
  2401. widget.deleteLater()
  2402. self.ui.notebook.removeTab(2)
  2403. # rebuild the Tools Tab
  2404. self.ui.tool_tab = QtWidgets.QWidget()
  2405. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2406. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2407. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2408. self.ui.tool_scroll_area = VerticalScrollArea()
  2409. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2410. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2411. # first remove all of them
  2412. self.remove_tools()
  2413. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2414. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2415. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2416. # third install all of them
  2417. self.install_tools()
  2418. self.log.debug("Tools are initialized.")
  2419. # def parse_system_fonts(self):
  2420. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2421. # 'params': []})
  2422. def connect_toolbar_signals(self):
  2423. """
  2424. Reconnect the signals to the actions in the toolbar.
  2425. This has to be done each time after the FlatCAM tools are removed/installed.
  2426. :return: None
  2427. """
  2428. # Toolbar
  2429. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2430. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2431. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2432. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2433. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2434. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2435. self.ui.replot_btn.triggered.connect(self.plot_all)
  2436. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2437. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2438. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2439. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2440. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2441. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2442. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2443. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2444. self.ui.delete_btn.triggered.connect(self.on_delete)
  2445. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2446. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2447. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2448. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2449. # Tools Toolbar Signals
  2450. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2451. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2452. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2453. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2454. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2455. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2456. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2457. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2458. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2459. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2460. def object2editor(self):
  2461. """
  2462. Send the current Geometry or Excellon object (if any) into the it's editor.
  2463. :return: None
  2464. """
  2465. self.report_usage("object2editor()")
  2466. edited_object = self.collection.get_active()
  2467. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2468. isinstance(edited_object, FlatCAMExcellon):
  2469. pass
  2470. else:
  2471. self.inform.emit('[WARNING_NOTCL] %s' %
  2472. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2473. return
  2474. if isinstance(edited_object, FlatCAMGeometry):
  2475. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2476. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2477. # we set the notebook to hidden
  2478. self.ui.splitter.setSizes([0, 1])
  2479. if edited_object.multigeo is True:
  2480. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2481. if len(edited_tools) > 1:
  2482. self.inform.emit('[WARNING_NOTCL] %s' %
  2483. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2484. "is not possible.\n"
  2485. "Edit only one geometry at a time."))
  2486. # determine the tool dia of the selected tool
  2487. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2488. # now find the key in the edited_object.tools that has this tooldia
  2489. multi_tool = 1
  2490. for tool in edited_object.tools:
  2491. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2492. multi_tool = tool
  2493. break
  2494. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2495. else:
  2496. self.geo_editor.edit_fcgeometry(edited_object)
  2497. # set call source to the Editor we go into
  2498. self.call_source = 'geo_editor'
  2499. elif isinstance(edited_object, FlatCAMExcellon):
  2500. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2501. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2502. if self.ui.splitter.sizes()[0] == 0:
  2503. self.ui.splitter.setSizes([1, 1])
  2504. self.exc_editor.edit_fcexcellon(edited_object)
  2505. # set call source to the Editor we go into
  2506. self.call_source = 'exc_editor'
  2507. elif isinstance(edited_object, FlatCAMGerber):
  2508. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2509. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2510. if self.ui.splitter.sizes()[0] == 0:
  2511. self.ui.splitter.setSizes([1, 1])
  2512. self.grb_editor.edit_fcgerber(edited_object)
  2513. # set call source to the Editor we go into
  2514. self.call_source = 'grb_editor'
  2515. # make sure that we can't select another object while in Editor Mode:
  2516. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2517. self.ui.project_frame.setDisabled(True)
  2518. # delete any selection shape that might be active as they are not relevant in Editor
  2519. self.delete_selection_shape()
  2520. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2521. self.ui.plot_tab_area.protectTab(0)
  2522. self.inform.emit('[WARNING_NOTCL] %s' %
  2523. _("Editor is activated ..."))
  2524. self.should_we_save = True
  2525. def editor2object(self, cleanup=None):
  2526. """
  2527. Transfers the Geometry or Excellon from it's editor to the current object.
  2528. :return: None
  2529. """
  2530. self.report_usage("editor2object()")
  2531. # do not update a geometry or excellon object unless it comes out of an editor
  2532. if self.call_source != 'app':
  2533. edited_obj = self.collection.get_active()
  2534. if cleanup is None:
  2535. msgbox = QtWidgets.QMessageBox()
  2536. msgbox.setText(_("Do you want to save the edited object?"))
  2537. msgbox.setWindowTitle(_("Close Editor"))
  2538. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2539. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2540. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2541. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2542. msgbox.setDefaultButton(bt_yes)
  2543. msgbox.exec_()
  2544. response = msgbox.clickedButton()
  2545. if response == bt_yes:
  2546. # clean the Tools Tab
  2547. self.ui.tool_scroll_area.takeWidget()
  2548. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2549. self.ui.notebook.setTabText(2, "Tool")
  2550. if isinstance(edited_obj, FlatCAMGeometry):
  2551. obj_type = "Geometry"
  2552. if cleanup is None:
  2553. self.geo_editor.update_fcgeometry(edited_obj)
  2554. self.geo_editor.update_options(edited_obj)
  2555. self.geo_editor.deactivate()
  2556. # update the geo object options so it is including the bounding box values
  2557. try:
  2558. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2559. edited_obj.options['xmin'] = xmin
  2560. edited_obj.options['ymin'] = ymin
  2561. edited_obj.options['xmax'] = xmax
  2562. edited_obj.options['ymax'] = ymax
  2563. except AttributeError as e:
  2564. self.inform.emit('[WARNING] %s' %
  2565. _("Object empty after edit."))
  2566. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2567. elif isinstance(edited_obj, FlatCAMGerber):
  2568. obj_type = "Gerber"
  2569. if cleanup is None:
  2570. self.grb_editor.update_fcgerber()
  2571. self.grb_editor.update_options(edited_obj)
  2572. self.grb_editor.deactivate_grb_editor()
  2573. # delete the old object (the source object) if it was an empty one
  2574. if len(edited_obj.solid_geometry) == 0:
  2575. old_name = edited_obj.options['name']
  2576. self.collection.set_active(old_name)
  2577. self.collection.delete_active()
  2578. elif isinstance(edited_obj, FlatCAMExcellon):
  2579. obj_type = "Excellon"
  2580. if cleanup is None:
  2581. self.exc_editor.update_fcexcellon(edited_obj)
  2582. self.exc_editor.update_options(edited_obj)
  2583. self.exc_editor.deactivate()
  2584. else:
  2585. self.inform.emit('[WARNING_NOTCL] %s' %
  2586. _("Select a Gerber, Geometry or Excellon Object to update."))
  2587. return
  2588. self.inform.emit('[selected] %s %s' %
  2589. (obj_type, _("is updated, returning to App...")))
  2590. elif response == bt_no:
  2591. # clean the Tools Tab
  2592. self.ui.tool_scroll_area.takeWidget()
  2593. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2594. self.ui.notebook.setTabText(2, "Tool")
  2595. if isinstance(edited_obj, FlatCAMGeometry):
  2596. self.geo_editor.deactivate()
  2597. elif isinstance(edited_obj, FlatCAMGerber):
  2598. self.grb_editor.deactivate_grb_editor()
  2599. elif isinstance(edited_obj, FlatCAMExcellon):
  2600. self.exc_editor.deactivate()
  2601. # set focus on the project tab
  2602. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2603. else:
  2604. self.inform.emit('[WARNING_NOTCL] %s' %
  2605. _("Select a Gerber, Geometry or Excellon Object to update."))
  2606. return
  2607. elif response == bt_cancel:
  2608. return
  2609. else:
  2610. if isinstance(edited_obj, FlatCAMGeometry):
  2611. self.geo_editor.deactivate()
  2612. elif isinstance(edited_obj, FlatCAMGerber):
  2613. self.grb_editor.deactivate_grb_editor()
  2614. elif isinstance(edited_obj, FlatCAMExcellon):
  2615. self.exc_editor.deactivate()
  2616. else:
  2617. self.inform.emit('[WARNING_NOTCL] %s' %
  2618. _("Select a Gerber, Geometry or Excellon Object to update."))
  2619. return
  2620. # if notebook is hidden we show it
  2621. if self.ui.splitter.sizes()[0] == 0:
  2622. self.ui.splitter.setSizes([1, 1])
  2623. # restore the call_source to app
  2624. self.call_source = 'app'
  2625. edited_obj.plot()
  2626. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2627. self.ui.plot_tab_area.protectTab(0)
  2628. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2629. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2630. self.ui.project_frame.setDisabled(False)
  2631. def get_last_folder(self):
  2632. """
  2633. Get the folder path from where the last file was opened.
  2634. :return: String, last opened folder path
  2635. """
  2636. return self.defaults["global_last_folder"]
  2637. def get_last_save_folder(self):
  2638. """
  2639. Get the folder path from where the last file was saved.
  2640. :return: String, last saved folder path
  2641. """
  2642. loc = self.defaults["global_last_save_folder"]
  2643. if loc is None:
  2644. loc = self.defaults["global_last_folder"]
  2645. if loc is None:
  2646. loc = os.path.dirname(__file__)
  2647. return loc
  2648. def report_usage(self, resource):
  2649. """
  2650. Increments usage counter for the given resource
  2651. in self.defaults['global_stats'].
  2652. :param resource: Name of the resource.
  2653. :return: None
  2654. """
  2655. if resource in self.defaults['global_stats']:
  2656. self.defaults['global_stats'][resource] += 1
  2657. else:
  2658. self.defaults['global_stats'][resource] = 1
  2659. def init_tcl(self):
  2660. """
  2661. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2662. :return: None
  2663. """
  2664. if hasattr(self, 'tcl'):
  2665. # self.tcl = None
  2666. # TODO we need to clean non default variables and procedures here
  2667. # new object cannot be used here as it will not remember values created for next passes,
  2668. # because tcl was execudted in old instance of TCL
  2669. pass
  2670. else:
  2671. self.tcl = tk.Tcl()
  2672. self.setup_shell()
  2673. self.log.debug("TCL Shell has been initialized.")
  2674. # TODO: This shouldn't be here.
  2675. class TclErrorException(Exception):
  2676. """
  2677. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2678. """
  2679. pass
  2680. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2681. """
  2682. Shows a message on the FlatCAM Shell
  2683. :param msg: Message to display.
  2684. :param show: Opens the shell.
  2685. :param error: Shows the message as an error.
  2686. :param warning: Shows the message as an warning.
  2687. :param success: Shows the message as an success.
  2688. :param selected: Indicate that something was selected on canvas
  2689. :return: None
  2690. """
  2691. if show:
  2692. self.ui.shell_dock.show()
  2693. try:
  2694. if error:
  2695. self.shell.append_error(msg + "\n")
  2696. elif warning:
  2697. self.shell.append_warning(msg + "\n")
  2698. elif success:
  2699. self.shell.append_success(msg + "\n")
  2700. elif selected:
  2701. self.shell.append_selected(msg + "\n")
  2702. else:
  2703. self.shell.append_output(msg + "\n")
  2704. except AttributeError:
  2705. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2706. def raise_tcl_unknown_error(self, unknownException):
  2707. """
  2708. Raise exception if is different type than TclErrorException
  2709. this is here mainly to show unknown errors inside TCL shell console.
  2710. :param unknownException:
  2711. :return:
  2712. """
  2713. if not isinstance(unknownException, self.TclErrorException):
  2714. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2715. else:
  2716. raise unknownException
  2717. def display_tcl_error(self, error, error_info=None):
  2718. """
  2719. Escape bracket [ with '\' otherwise there is error
  2720. "ERROR: missing close-bracket" instead of real error
  2721. :param error: it may be text or exception
  2722. :param error_info: Some informations about the error
  2723. :return: None
  2724. """
  2725. if isinstance(error, Exception):
  2726. exc_type, exc_value, exc_traceback = error_info
  2727. if not isinstance(error, self.TclErrorException):
  2728. show_trace = 1
  2729. else:
  2730. show_trace = int(self.defaults['global_verbose_error_level'])
  2731. if show_trace > 0:
  2732. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2733. trc_formated = []
  2734. for a in reversed(trc):
  2735. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2736. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2737. else:
  2738. text = "%s" % error
  2739. else:
  2740. text = error
  2741. text = text.replace('[', '\\[').replace('"', '\\"')
  2742. self.tcl.eval('return -code error "%s"' % text)
  2743. def raise_tcl_error(self, text):
  2744. """
  2745. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2746. :param text: text of error
  2747. :return: raise exception
  2748. """
  2749. self.display_tcl_error(text)
  2750. raise self.TclErrorException(text)
  2751. def exec_command(self, text, no_echo=False):
  2752. """
  2753. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2754. Also handles execution in separated threads
  2755. :param text: FlatCAM TclCommand with parameters
  2756. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2757. will create crashes of the _Expandable_Edit widget
  2758. :return: output if there was any
  2759. """
  2760. self.report_usage('exec_command')
  2761. result = self.exec_command_test(text, False, no_echo=no_echo)
  2762. # MS: added this method call so the geometry is updated once the TCL command is executed
  2763. # if no_plot is None:
  2764. # self.plot_all()
  2765. return result
  2766. def exec_command_test(self, text, reraise=True, no_echo=False):
  2767. """
  2768. Same as exec_command(...) with additional control over exceptions.
  2769. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2770. :param text: Input command
  2771. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2772. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2773. will create crashes of the _Expandable_Edit widget
  2774. :return: Output from the command
  2775. """
  2776. tcl_command_string = str(text)
  2777. try:
  2778. if no_echo is False:
  2779. self.shell.open_proccessing() # Disables input box.
  2780. result = self.tcl.eval(str(tcl_command_string))
  2781. if result != 'None' and no_echo is False:
  2782. self.shell.append_output(result + '\n')
  2783. except tk.TclError as e:
  2784. # This will display more precise answer if something in TCL shell fails
  2785. result = self.tcl.eval("set errorInfo")
  2786. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2787. if no_echo is False:
  2788. self.shell.append_error('ERROR: ' + result + '\n')
  2789. # Show error in console and just return or in test raise exception
  2790. if reraise:
  2791. raise e
  2792. finally:
  2793. if no_echo is False:
  2794. self.shell.close_proccessing()
  2795. pass
  2796. return result
  2797. # """
  2798. # Code below is unsused. Saved for later.
  2799. # """
  2800. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2801. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2802. # self.log.debug(parts)
  2803. # try:
  2804. # if parts[0] not in commands:
  2805. # self.shell.append_error("Unknown command\n")
  2806. # return
  2807. #
  2808. # #import inspect
  2809. # #inspect.getargspec(someMethod)
  2810. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2811. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2812. # self.shell.append_error(
  2813. # "Command %s takes %d arguments. %d given.\n" %
  2814. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2815. # )
  2816. # return
  2817. #
  2818. # cmdfcn = commands[parts[0]]["fcn"]
  2819. # cmdconv = commands[parts[0]]["converters"]
  2820. # if len(parts) - 1 > 0:
  2821. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2822. # else:
  2823. # retval = cmdfcn()
  2824. # retfcn = commands[parts[0]]["retfcn"]
  2825. # if retval and retfcn(retval):
  2826. # self.shell.append_output(retfcn(retval) + "\n")
  2827. #
  2828. # except Exception as e:
  2829. # #self.shell.append_error(''.join(traceback.format_exc()))
  2830. # #self.shell.append_error("?\n")
  2831. # self.shell.append_error(str(e) + "\n")
  2832. def info(self, msg):
  2833. """
  2834. Informs the user. Normally on the status bar, optionally
  2835. also on the shell.
  2836. :param msg: Text to write.
  2837. :return: None
  2838. """
  2839. # Type of message in brackets at the beginning of the message.
  2840. match = re.search("\[([^\]]+)\](.*)", msg)
  2841. if match:
  2842. level = match.group(1)
  2843. msg_ = match.group(2)
  2844. self.ui.fcinfo.set_status(str(msg_), level=level)
  2845. if level.lower() == "error":
  2846. self.shell_message(msg, error=True, show=True)
  2847. elif level.lower() == "warning":
  2848. self.shell_message(msg, warning=True, show=True)
  2849. elif level.lower() == "error_notcl":
  2850. self.shell_message(msg, error=True, show=False)
  2851. elif level.lower() == "warning_notcl":
  2852. self.shell_message(msg, warning=True, show=False)
  2853. elif level.lower() == "success":
  2854. self.shell_message(msg, success=True, show=False)
  2855. elif level.lower() == "selected":
  2856. self.shell_message(msg, selected=True, show=False)
  2857. else:
  2858. self.shell_message(msg, show=False)
  2859. else:
  2860. self.ui.fcinfo.set_status(str(msg), level="info")
  2861. # make sure that if the message is to clear the infobar with a space
  2862. # is not printed over and over on the shell
  2863. if msg != '':
  2864. self.shell_message(msg)
  2865. def restore_toolbar_view(self):
  2866. """
  2867. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2868. was saved in the defaults dictionary.
  2869. :return: None
  2870. """
  2871. tb = self.defaults["global_toolbar_view"]
  2872. if tb & 1:
  2873. self.ui.toolbarfile.setVisible(True)
  2874. else:
  2875. self.ui.toolbarfile.setVisible(False)
  2876. if tb & 2:
  2877. self.ui.toolbargeo.setVisible(True)
  2878. else:
  2879. self.ui.toolbargeo.setVisible(False)
  2880. if tb & 4:
  2881. self.ui.toolbarview.setVisible(True)
  2882. else:
  2883. self.ui.toolbarview.setVisible(False)
  2884. if tb & 8:
  2885. self.ui.toolbartools.setVisible(True)
  2886. else:
  2887. self.ui.toolbartools.setVisible(False)
  2888. if tb & 16:
  2889. self.ui.exc_edit_toolbar.setVisible(True)
  2890. else:
  2891. self.ui.exc_edit_toolbar.setVisible(False)
  2892. if tb & 32:
  2893. self.ui.geo_edit_toolbar.setVisible(True)
  2894. else:
  2895. self.ui.geo_edit_toolbar.setVisible(False)
  2896. if tb & 64:
  2897. self.ui.grb_edit_toolbar.setVisible(True)
  2898. else:
  2899. self.ui.grb_edit_toolbar.setVisible(False)
  2900. if tb & 128:
  2901. self.ui.snap_toolbar.setVisible(True)
  2902. else:
  2903. self.ui.snap_toolbar.setVisible(False)
  2904. if tb & 256:
  2905. self.ui.toolbarshell.setVisible(True)
  2906. else:
  2907. self.ui.toolbarshell.setVisible(False)
  2908. def load_defaults(self, filename):
  2909. """
  2910. Loads the aplication's default settings from current_defaults.FlatConfig into
  2911. ``self.defaults``.
  2912. :return: None
  2913. """
  2914. try:
  2915. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2916. options = f.read()
  2917. f.close()
  2918. except IOError:
  2919. self.log.error("Could not load defaults file.")
  2920. self.inform.emit('[ERROR] %s' %
  2921. _("Could not load defaults file."))
  2922. # in case the defaults file can't be loaded, show all toolbars
  2923. self.defaults["global_toolbar_view"] = 511
  2924. return
  2925. try:
  2926. defaults = json.loads(options)
  2927. except:
  2928. # in case the defaults file can't be loaded, show all toolbars
  2929. self.defaults["global_toolbar_view"] = 511
  2930. e = sys.exc_info()[0]
  2931. App.log.error(str(e))
  2932. self.inform.emit('[ERROR] %s' %
  2933. _("Failed to parse defaults file."))
  2934. return
  2935. self.defaults.update(defaults)
  2936. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2937. # restore the toolbar view
  2938. self.restore_toolbar_view()
  2939. def on_import_preferences(self):
  2940. """
  2941. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2942. ``self.defaults``.
  2943. :return: None
  2944. """
  2945. self.report_usage("on_import_preferences")
  2946. App.log.debug("on_import_preferences()")
  2947. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2948. try:
  2949. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2950. directory=self.data_path,
  2951. filter=filter_)
  2952. except TypeError:
  2953. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2954. filter=filter_)
  2955. filename = str(filename)
  2956. if filename == "":
  2957. self.inform.emit('[WARNING_NOTCL] %s' %
  2958. _("FlatCAM preferences import cancelled."))
  2959. else:
  2960. try:
  2961. f = open(filename)
  2962. options = f.read()
  2963. f.close()
  2964. except IOError:
  2965. self.log.error("Could not load defaults file.")
  2966. self.inform.emit('[ERROR_NOTCL] %s' %
  2967. _("Could not load defaults file."))
  2968. return
  2969. try:
  2970. defaults_from_file = json.loads(options)
  2971. except Exception as e:
  2972. e = sys.exc_info()[0]
  2973. App.log.error(str(e))
  2974. self.inform.emit('[ERROR_NOTCL] %s' %
  2975. _("Failed to parse defaults file."))
  2976. return
  2977. self.defaults.update(defaults_from_file)
  2978. self.on_preferences_edited()
  2979. self.inform.emit('[success] %s: %s' %
  2980. (_("Imported Defaults from"), filename))
  2981. def on_export_preferences(self):
  2982. """
  2983. Save the defaults dictionary to a file.
  2984. :return: None
  2985. """
  2986. self.report_usage("on_export_preferences")
  2987. App.log.debug("on_export_preferences()")
  2988. defaults_file_content = None
  2989. self.date = str(datetime.today()).rpartition('.')[0]
  2990. self.date = ''.join(c for c in self.date if c not in ':-')
  2991. self.date = self.date.replace(' ', '_')
  2992. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2993. try:
  2994. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2995. caption=_("Export FlatCAM Preferences"),
  2996. directory=self.data_path + '/preferences_' + self.date,
  2997. filter=filter__
  2998. )
  2999. except TypeError:
  3000. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3001. filter=filter__)
  3002. filename = str(filename)
  3003. defaults_from_file = {}
  3004. if filename == "":
  3005. self.inform.emit('[WARNING_NOTCL] %s' %
  3006. _("FlatCAM preferences export cancelled."))
  3007. return
  3008. else:
  3009. try:
  3010. f = open(filename, 'w')
  3011. defaults_file_content = f.read()
  3012. f.close()
  3013. except PermissionError:
  3014. self.inform.emit('[WARNING] %s' %
  3015. _("Permission denied, saving not possible.\n"
  3016. "Most likely another app is holding the file open and not accessible."))
  3017. return
  3018. except IOError:
  3019. App.log.debug('Creating a new preferences file ...')
  3020. f = open(filename, 'w')
  3021. json.dump({}, f)
  3022. f.close()
  3023. except:
  3024. e = sys.exc_info()[0]
  3025. App.log.error("Could not load defaults file.")
  3026. App.log.error(str(e))
  3027. self.inform.emit('[ERROR_NOTCL] %s' %
  3028. _("Could not load preferences file."))
  3029. return
  3030. try:
  3031. defaults_from_file = json.loads(defaults_file_content)
  3032. except:
  3033. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3034. # Update options
  3035. self.defaults_read_form()
  3036. defaults_from_file.update(self.defaults)
  3037. self.propagate_defaults(silent=True)
  3038. # Save update options
  3039. try:
  3040. f = open(filename, "w")
  3041. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3042. f.close()
  3043. except:
  3044. self.inform.emit('[ERROR_NOTCL] %s' %
  3045. _("Failed to write defaults to file."))
  3046. return
  3047. if self.defaults["global_open_style"] is False:
  3048. self.file_opened.emit("preferences", filename)
  3049. self.file_saved.emit("preferences", filename)
  3050. self.inform.emit('[success] %s: %s' %
  3051. (_("Exported preferences to"), filename))
  3052. def on_preferences_open_folder(self):
  3053. """
  3054. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3055. :return: None
  3056. """
  3057. self.report_usage("on_preferences_open_folder()")
  3058. if sys.platform == 'win32':
  3059. subprocess.Popen('explorer %s' % self.data_path)
  3060. elif sys.platform == 'darwin':
  3061. os.system('open "%s"' % self.data_path)
  3062. else:
  3063. subprocess.Popen(['xdg-open', self.data_path])
  3064. self.inform.emit('[success] %s' %
  3065. _("FlatCAM Preferences Folder opened."))
  3066. def save_geometry(self, x, y, width, height, notebook_width):
  3067. """
  3068. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3069. launch of the application.
  3070. :param x: X position of the main window
  3071. :param y: Y position of the main window
  3072. :param width: width of the main window
  3073. :param height: height of the main window
  3074. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3075. :return: None
  3076. """
  3077. self.defaults["global_def_win_x"] = x
  3078. self.defaults["global_def_win_y"] = y
  3079. self.defaults["global_def_win_w"] = width
  3080. self.defaults["global_def_win_h"] = height
  3081. self.defaults["global_def_notebook_width"] = notebook_width
  3082. self.save_defaults()
  3083. def message_dialog(self, title, message, kind="info"):
  3084. """
  3085. Builds and show a custom QMessageBox to be used in FlatCAM.
  3086. :param title: title of the QMessageBox
  3087. :param message: message to be displayed
  3088. :param kind: type of QMessageBox; will display a specific icon.
  3089. :return:
  3090. """
  3091. icon = {"info": QtWidgets.QMessageBox.Information,
  3092. "warning": QtWidgets.QMessageBox.Warning,
  3093. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3094. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3095. dlg.setText(message)
  3096. dlg.exec_()
  3097. def register_recent(self, kind, filename):
  3098. """
  3099. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3100. dictionary.
  3101. :param kind: type of file that was opened
  3102. :param filename: the path and file name for the file that was opened
  3103. :return:
  3104. """
  3105. self.log.debug("register_recent()")
  3106. self.log.debug(" %s" % kind)
  3107. self.log.debug(" %s" % filename)
  3108. record = {'kind': str(kind), 'filename': str(filename)}
  3109. if record in self.recent:
  3110. return
  3111. if record in self.recent_projects:
  3112. return
  3113. if record['kind'] == 'project':
  3114. self.recent_projects.insert(0, record)
  3115. else:
  3116. self.recent.insert(0, record)
  3117. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3118. self.recent.pop()
  3119. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3120. self.recent_projects.pop()
  3121. try:
  3122. f = open(self.data_path + '/recent.json', 'w')
  3123. except IOError:
  3124. App.log.error("Failed to open recent items file for writing.")
  3125. self.inform.emit('[ERROR_NOTCL] %s' %
  3126. _('Failed to open recent files file for writing.'))
  3127. return
  3128. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3129. f.close()
  3130. try:
  3131. fp = open(self.data_path + '/recent_projects.json', 'w')
  3132. except IOError:
  3133. App.log.error("Failed to open recent items file for writing.")
  3134. self.inform.emit('[ERROR_NOTCL] %s' %
  3135. _('Failed to open recent projects file for writing.'))
  3136. return
  3137. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3138. fp.close()
  3139. # Re-build the recent items menu
  3140. self.setup_recent_items()
  3141. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3142. """
  3143. Creates a new specialized FlatCAMObj and attaches it to the application,
  3144. this is, updates the GUI accordingly, any other records and plots it.
  3145. This method is thread-safe.
  3146. Notes:
  3147. * If the name is in use, the self.collection will modify it
  3148. when appending it to the collection. There is no need to handle
  3149. name conflicts here.
  3150. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3151. :type kind: str
  3152. :param name: Name for the object.
  3153. :type name: str
  3154. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3155. The function is called with 2 parameters: the new object and the App instance.
  3156. :type initialize: function
  3157. :param active:
  3158. :param fit:
  3159. :param plot: If to plot the resulting object
  3160. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3161. self.colleaction
  3162. :return: None
  3163. :rtype: None
  3164. """
  3165. App.log.debug("new_object()")
  3166. obj_plot = plot
  3167. obj_autoselected = autoselected
  3168. t0 = time.time() # Debug
  3169. # ## Create object
  3170. classdict = {
  3171. "gerber": FlatCAMGerber,
  3172. "excellon": FlatCAMExcellon,
  3173. "cncjob": FlatCAMCNCjob,
  3174. "geometry": FlatCAMGeometry
  3175. }
  3176. App.log.debug("Calling object constructor...")
  3177. obj = classdict[kind](name)
  3178. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3179. # Set options from "Project options" form
  3180. self.options_read_form()
  3181. # IMPORTANT
  3182. # The key names in defaults and options dictionary's are not random:
  3183. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3184. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3185. # the options from project options form into the self.options. After that, below, depending on the type of
  3186. # object that is created, it will strip the name of the object and the underline (if the original key was
  3187. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3188. # "toolchange"
  3189. for option in self.options:
  3190. if option.find(kind + "_") == 0:
  3191. oname = option[len(kind) + 1:]
  3192. obj.options[oname] = self.options[option]
  3193. obj.isHovering = False
  3194. obj.notHovering = True
  3195. # Initialize as per user request
  3196. # User must take care to implement initialize
  3197. # in a thread-safe way as is is likely that we
  3198. # have been invoked in a separate thread.
  3199. t1 = time.time()
  3200. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3201. try:
  3202. return_value = initialize(obj, self)
  3203. except Exception as e:
  3204. msg = '[ERROR_NOTCL] %s' % \
  3205. _("An internal error has ocurred. See shell.\n")
  3206. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3207. msg += traceback.format_exc()
  3208. self.inform.emit(msg)
  3209. # if str(e) == "Empty Geometry":
  3210. # self.inform.emit("[ERROR_NOTCL] )
  3211. # else:
  3212. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3213. return "fail"
  3214. t2 = time.time()
  3215. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3216. if return_value == 'fail':
  3217. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3218. return "fail"
  3219. # Check units and convert if necessary
  3220. # This condition CAN be true because initialize() can change obj.units
  3221. if self.options["units"].upper() != obj.units.upper():
  3222. self.inform.emit('%s: %s' %
  3223. (_("Converting units to "), self.options["units"]))
  3224. obj.convert_units(self.options["units"])
  3225. t3 = time.time()
  3226. self.log.debug("%f seconds converting units." % (t3 - t2))
  3227. # Create the bounding box for the object and then add the results to the obj.options
  3228. try:
  3229. xmin, ymin, xmax, ymax = obj.bounds()
  3230. obj.options['xmin'] = xmin
  3231. obj.options['ymin'] = ymin
  3232. obj.options['xmax'] = xmax
  3233. obj.options['ymax'] = ymax
  3234. except Exception as e:
  3235. log.warning("The object has no bounds properties. %s" % str(e))
  3236. return "fail"
  3237. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3238. # Move the object to the main thread and let the app know that it is available.
  3239. obj.moveToThread(self.main_thread)
  3240. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3241. return obj
  3242. def new_excellon_object(self):
  3243. """
  3244. Creates a new, blank Excellon object.
  3245. :return: None
  3246. """
  3247. self.report_usage("new_excellon_object()")
  3248. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3249. def new_geometry_object(self):
  3250. """
  3251. Creates a new, blank and single-tool Geometry object.
  3252. :return: None
  3253. """
  3254. self.report_usage("new_geometry_object()")
  3255. def initialize(obj, self):
  3256. obj.multitool = False
  3257. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3258. def new_gerber_object(self):
  3259. """
  3260. Creates a new, blank Gerber object.
  3261. :return: None
  3262. """
  3263. self.report_usage("new_gerber_object()")
  3264. def initialize(grb_obj, self):
  3265. grb_obj.multitool = False
  3266. grb_obj.source_file = []
  3267. grb_obj.multigeo = False
  3268. grb_obj.follow = False
  3269. grb_obj.apertures = {}
  3270. grb_obj.solid_geometry = []
  3271. try:
  3272. grb_obj.options['xmin'] = 0
  3273. grb_obj.options['ymin'] = 0
  3274. grb_obj.options['xmax'] = 0
  3275. grb_obj.options['ymax'] = 0
  3276. except KeyError:
  3277. pass
  3278. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3279. def on_object_created(self, obj, plot, autoselect):
  3280. """
  3281. Event callback for object creation.
  3282. It will add the new object to the collection. After that it will plot the object in a threaded way
  3283. :param obj: The newly created FlatCAM object.
  3284. :param plot: if the newly create object t obe plotted
  3285. :param autoselect: if the newly created object to be autoselected after creation
  3286. :return: None
  3287. """
  3288. t0 = time.time() # DEBUG
  3289. self.log.debug("on_object_created()")
  3290. # The Collection might change the name if there is a collision
  3291. self.collection.append(obj)
  3292. # after adding the object to the collection always update the list of objects that are in the collection
  3293. self.all_objects_list = self.collection.get_list()
  3294. # self.inform.emit('[selected] %s created & selected: %s' %
  3295. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3296. if obj.kind == 'gerber':
  3297. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3298. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3299. elif obj.kind == 'excellon':
  3300. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3301. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3302. elif obj.kind == 'cncjob':
  3303. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3304. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3305. elif obj.kind == 'geometry':
  3306. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3307. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3308. # update the SHELL auto-completer model with the name of the new object
  3309. self.myKeywords.append(obj.options['name'])
  3310. self.shell._edit.set_model_data(self.myKeywords)
  3311. self.ui.code_editor.set_model_data(self.myKeywords)
  3312. if autoselect:
  3313. # select the just opened object but deselect the previous ones
  3314. self.collection.set_all_inactive()
  3315. self.collection.set_active(obj.options["name"])
  3316. else:
  3317. self.collection.set_all_inactive()
  3318. # here it is done the object plotting
  3319. def worker_task(t_obj):
  3320. with self.proc_container.new(_("Plotting")):
  3321. if isinstance(t_obj, FlatCAMCNCjob):
  3322. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3323. else:
  3324. t_obj.plot()
  3325. t1 = time.time() # DEBUG
  3326. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3327. self.object_plotted.emit(t_obj)
  3328. # Send to worker
  3329. # self.worker.add_task(worker_task, [self])
  3330. if plot is True:
  3331. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3332. def on_object_changed(self, obj):
  3333. """
  3334. Called whenever the geometry of the object was changed in some way.
  3335. This require the update of it's bounding values so it can be the selected on canvas.
  3336. Update the bounding box data from obj.options
  3337. :param obj: the object that was changed
  3338. :return: None
  3339. """
  3340. xmin, ymin, xmax, ymax = obj.bounds()
  3341. obj.options['xmin'] = xmin
  3342. obj.options['ymin'] = ymin
  3343. obj.options['xmax'] = xmax
  3344. obj.options['ymax'] = ymax
  3345. log.debug("Object changed, updating the bounding box data on self.options")
  3346. # delete the old selection shape
  3347. self.delete_selection_shape()
  3348. self.should_we_save = True
  3349. def on_object_plotted(self, obj):
  3350. """
  3351. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3352. :param obj: object to be fit into view
  3353. :return: None
  3354. """
  3355. self.on_zoom_fit(None)
  3356. def options_read_form(self):
  3357. """
  3358. Same as it's equivalent from the defaults.
  3359. self.options use to store the preferences per project. No longer used.
  3360. :return: None
  3361. """
  3362. for option in self.options_form_fields:
  3363. self.options[option] = self.options_form_fields[option].get_value()
  3364. def options_write_form(self):
  3365. """
  3366. Same as it's equivalent from the defaults.
  3367. self.options use to store the preferences per project. No longer used.
  3368. :return: None
  3369. """
  3370. for option in self.options:
  3371. self.options_write_form_field(option)
  3372. def options_write_form_field(self, field):
  3373. """
  3374. Same as it's equivalent from the defaults.
  3375. self.options use to store the preferences per project. No longer used.
  3376. :return: None
  3377. """
  3378. try:
  3379. self.options_form_fields[field].set_value(self.options[field])
  3380. except KeyError:
  3381. # Changed from error to debug. This allows to have data stored
  3382. # which is not user-editable.
  3383. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3384. pass
  3385. def on_about(self):
  3386. """
  3387. Displays the "about" dialog found in the Menu --> Help.
  3388. :return: None
  3389. """
  3390. self.report_usage("on_about")
  3391. version = self.version
  3392. version_date = self.version_date
  3393. beta = self.beta
  3394. class AboutDialog(QtWidgets.QDialog):
  3395. def __init__(self, parent=None):
  3396. QtWidgets.QDialog.__init__(self, parent)
  3397. # Icon and title
  3398. self.setWindowIcon(parent.app_icon)
  3399. self.setWindowTitle(_("About FlatCAM"))
  3400. self.resize(600, 200)
  3401. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3402. # self.setStyleSheet(
  3403. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3404. # "background-attachment: fixed"
  3405. # )
  3406. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3407. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3408. # palette = QtGui.QPalette()
  3409. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3410. # self.setPalette(palette)
  3411. logo = QtWidgets.QLabel()
  3412. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3413. title = QtWidgets.QLabel(
  3414. "<font size=8><B>FlatCAM</B></font><BR>"
  3415. "{title}<BR>"
  3416. "<BR>"
  3417. "<BR>"
  3418. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3419. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3420. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3421. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3422. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3423. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3424. "<B>{issue}</B></a><BR>".format(
  3425. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3426. devel=_("Development"),
  3427. down=_("DOWNLOAD"),
  3428. issue=_("Issue tracker"))
  3429. )
  3430. title.setOpenExternalLinks(True)
  3431. closebtn = QtWidgets.QPushButton(_("Close"))
  3432. tab_widget = QtWidgets.QTabWidget()
  3433. description_label = QtWidgets.QLabel(
  3434. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3435. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3436. version=version,
  3437. beta=('BETA' if beta else ''),
  3438. date=version_date,
  3439. arch=platform.architecture()[0])
  3440. )
  3441. description_label.setOpenExternalLinks(True)
  3442. license_label = QtWidgets.QLabel(
  3443. _(
  3444. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3445. 'Licensed under the MIT license:\n'
  3446. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3447. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3448. 'of this software and associated documentation files (the "Software"), to deal\n'
  3449. 'in the Software without restriction, including without limitation the rights\n'
  3450. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3451. 'copies of the Software, and to permit persons to whom the Software is\n'
  3452. ' furnished to do so, subject to the following conditions:\n\n'
  3453. 'The above copyright notice and this permission notice shall be included in\n'
  3454. 'all copies or substantial portions of the Software.\n\n'
  3455. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3456. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3457. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3458. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3459. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3460. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3461. 'THE SOFTWARE.'
  3462. )
  3463. )
  3464. license_label.setOpenExternalLinks(True)
  3465. # layouts
  3466. layout1 = QtWidgets.QVBoxLayout()
  3467. layout1_1 = QtWidgets.QHBoxLayout()
  3468. layout1_2 = QtWidgets.QHBoxLayout()
  3469. layout2 = QtWidgets.QHBoxLayout()
  3470. layout3 = QtWidgets.QHBoxLayout()
  3471. self.setLayout(layout1)
  3472. layout1.addLayout(layout1_1)
  3473. layout1.addLayout(layout1_2)
  3474. layout1.addLayout(layout2)
  3475. layout1.addLayout(layout3)
  3476. layout1_1.addStretch()
  3477. layout1_1.addWidget(description_label)
  3478. layout1_2.addWidget(tab_widget)
  3479. self.splash_tab = QtWidgets.QWidget()
  3480. self.splash_tab.setObjectName("splash_about")
  3481. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3482. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3483. tab_widget.addTab(self.splash_tab, _("Splash"))
  3484. self.programmmers_tab = QtWidgets.QWidget()
  3485. self.programmmers_tab.setObjectName("programmers_about")
  3486. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3487. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3488. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3489. self.translators_tab = QtWidgets.QWidget()
  3490. self.translators_tab.setObjectName("translators_about")
  3491. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3492. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3493. tab_widget.addTab(self.translators_tab, _("Translators"))
  3494. self.license_tab = QtWidgets.QWidget()
  3495. self.license_tab.setObjectName("license_about")
  3496. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3497. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3498. tab_widget.addTab(self.license_tab, _("License"))
  3499. self.splash_tab_layout.addWidget(logo, stretch=0)
  3500. self.splash_tab_layout.addWidget(title, stretch=1)
  3501. pal = QtGui.QPalette()
  3502. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3503. self.prog_form_lay = QtWidgets.QFormLayout()
  3504. self.prog_form_lay.setHorizontalSpacing(20)
  3505. prog_widget = QtWidgets.QWidget()
  3506. prog_widget.setLayout(self.prog_form_lay)
  3507. prog_scroll = QtWidgets.QScrollArea()
  3508. prog_scroll.setWidget(prog_widget)
  3509. prog_scroll.setWidgetResizable(True)
  3510. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3511. prog_scroll.setPalette(pal)
  3512. self.programmmers_tab_layout.addWidget(prog_scroll)
  3513. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3514. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3515. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3516. QtWidgets.QLabel('%s' % _("Program Author")))
  3517. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3518. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3519. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3520. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3521. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3522. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3523. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3524. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3525. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3526. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3527. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3528. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3529. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3530. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3531. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3532. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3533. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3534. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3535. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3536. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3537. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3538. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3539. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3540. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3541. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3542. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3543. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3544. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3545. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3546. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3547. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3548. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3549. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3550. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3551. self.translator_grid_lay = QtWidgets.QGridLayout()
  3552. # trans_widget = QtWidgets.QWidget()
  3553. # trans_widget.setLayout(self.translator_grid_lay)
  3554. # self.translators_tab_layout.addWidget(trans_widget)
  3555. # self.translators_tab_layout.addStretch()
  3556. trans_widget = QtWidgets.QWidget()
  3557. trans_widget.setLayout(self.translator_grid_lay)
  3558. trans_scroll = QtWidgets.QScrollArea()
  3559. trans_scroll.setWidget(trans_widget)
  3560. trans_scroll.setWidgetResizable(True)
  3561. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3562. trans_scroll.setPalette(pal)
  3563. self.translators_tab_layout.addWidget(trans_scroll)
  3564. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3565. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3566. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3567. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3568. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3569. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3570. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3571. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3572. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3573. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3574. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3575. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3576. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3577. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3578. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3579. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3580. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3581. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3582. self.translator_grid_lay.setColumnStretch(0, 0)
  3583. self.translators_tab_layout.addStretch()
  3584. self.license_tab_layout.addWidget(license_label)
  3585. self.license_tab_layout.addStretch()
  3586. layout3.addStretch()
  3587. layout3.addWidget(closebtn)
  3588. closebtn.clicked.connect(self.accept)
  3589. AboutDialog(self.ui).exec_()
  3590. def on_file_savedefaults(self):
  3591. """
  3592. Callback for menu item File->Save Defaults. Saves application default options
  3593. ``self.defaults`` to current_defaults.FlatConfig.
  3594. :return: None
  3595. """
  3596. self.save_defaults()
  3597. # def on_app_exit(self):
  3598. # self.report_usage("on_app_exit()")
  3599. #
  3600. # if self.collection.get_list():
  3601. # msgbox = QtWidgets.QMessageBox()
  3602. # # msgbox.setText("<B>Save changes ...</B>")
  3603. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3604. # "\n"
  3605. # "Do you want to Save the project?")
  3606. # msgbox.setWindowTitle("Save changes")
  3607. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3608. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3609. # QtWidgets.QMessageBox.Cancel)
  3610. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3611. #
  3612. # response = msgbox.exec_()
  3613. #
  3614. # if response == QtWidgets.QMessageBox.Yes:
  3615. # self.on_file_saveprojectas(thread=False)
  3616. # elif response == QtWidgets.QMessageBox.Cancel:
  3617. # return
  3618. # self.save_defaults()
  3619. # else:
  3620. # self.save_defaults()
  3621. # log.debug("Application defaults saved ... Exit event.")
  3622. # QtWidgets.qApp.quit()
  3623. def save_defaults(self, silent=False, data_path=None):
  3624. """
  3625. Saves application default options
  3626. ``self.defaults`` to current_defaults.FlatConfig file.
  3627. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3628. used at the next launch of the application.
  3629. :param silent: whether to display a message in status bar or not; boolean
  3630. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3631. When the application is portable it should be a mobile location.
  3632. :return: None
  3633. """
  3634. self.report_usage("save_defaults")
  3635. if data_path is None:
  3636. data_path = self.data_path
  3637. # Read options from file
  3638. try:
  3639. f = open(data_path + "/current_defaults.FlatConfig")
  3640. defaults_file_content = f.read()
  3641. f.close()
  3642. except:
  3643. e = sys.exc_info()[0]
  3644. App.log.error("Could not load defaults file.")
  3645. App.log.error(str(e))
  3646. self.inform.emit('[ERROR_NOTCL] %s' %
  3647. _("Could not load defaults file."))
  3648. return
  3649. try:
  3650. defaults = json.loads(defaults_file_content)
  3651. except:
  3652. e = sys.exc_info()[0]
  3653. App.log.error("Failed to parse defaults file.")
  3654. App.log.error(str(e))
  3655. self.inform.emit('[ERROR_NOTCL] %s' %
  3656. _("Failed to parse defaults file."))
  3657. return
  3658. # Update options
  3659. self.defaults_read_form()
  3660. defaults.update(self.defaults)
  3661. self.propagate_defaults(silent=True)
  3662. # Save the toolbar view
  3663. tb_status = 0
  3664. if self.ui.toolbarfile.isVisible():
  3665. tb_status += 1
  3666. if self.ui.toolbargeo.isVisible():
  3667. tb_status += 2
  3668. if self.ui.toolbarview.isVisible():
  3669. tb_status += 4
  3670. if self.ui.toolbartools.isVisible():
  3671. tb_status += 8
  3672. if self.ui.exc_edit_toolbar.isVisible():
  3673. tb_status += 16
  3674. if self.ui.geo_edit_toolbar.isVisible():
  3675. tb_status += 32
  3676. if self.ui.grb_edit_toolbar.isVisible():
  3677. tb_status += 64
  3678. if self.ui.snap_toolbar.isVisible():
  3679. tb_status += 128
  3680. if self.ui.toolbarshell.isVisible():
  3681. tb_status += 256
  3682. self.defaults["global_toolbar_view"] = tb_status
  3683. # Save update options
  3684. try:
  3685. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3686. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3687. f.close()
  3688. except:
  3689. self.inform.emit('[ERROR_NOTCL] %s' %
  3690. _("Failed to write defaults to file."))
  3691. return
  3692. if not silent:
  3693. self.inform.emit('[success] %s' %
  3694. _("Preferences saved."))
  3695. def save_factory_defaults(self, silent=False, data_path=None):
  3696. """
  3697. Saves application factory default options
  3698. ``self.defaults`` to factory_defaults.FlatConfig.
  3699. It's a one time job done just after the first install.
  3700. :param silent: whether to display a message in status bar or not; boolean
  3701. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3702. When the application is portable it should be a mobile location.
  3703. :return: None
  3704. """
  3705. self.report_usage("save_factory_defaults")
  3706. if data_path is None:
  3707. data_path = self.data_path
  3708. # Read options from file
  3709. try:
  3710. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3711. factory_defaults_file_content = f_f_def.read()
  3712. f_f_def.close()
  3713. except:
  3714. e = sys.exc_info()[0]
  3715. App.log.error("Could not load factory defaults file.")
  3716. App.log.error(str(e))
  3717. self.inform.emit('[ERROR_NOTCL] %s' %
  3718. _("Could not load factory defaults file."))
  3719. return
  3720. try:
  3721. factory_defaults = json.loads(factory_defaults_file_content)
  3722. except:
  3723. e = sys.exc_info()[0]
  3724. App.log.error("Failed to parse factory defaults file.")
  3725. App.log.error(str(e))
  3726. self.inform.emit('[ERROR_NOTCL] %s' %
  3727. _("Failed to parse factory defaults file."))
  3728. return
  3729. # Update options
  3730. self.defaults_read_form()
  3731. factory_defaults.update(self.defaults)
  3732. self.propagate_defaults(silent=True)
  3733. # Save update options
  3734. try:
  3735. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3736. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3737. f_f_def_s.close()
  3738. except:
  3739. self.inform.emit('[ERROR_NOTCL] %s' %
  3740. _("Failed to write factory defaults to file."))
  3741. return
  3742. if silent is False:
  3743. self.inform.emit(_("Factory defaults saved."))
  3744. def final_save(self):
  3745. """
  3746. Callback for doing a preferences save to file whenever the application is about to quit.
  3747. If the project has changes, it will ask the user to save the project.
  3748. :return: None
  3749. """
  3750. if self.save_in_progress:
  3751. self.inform.emit('[WARNING_NOTCL] %s' %
  3752. _("Application is saving the project. Please wait ..."))
  3753. return
  3754. if self.should_we_save and self.collection.get_list():
  3755. msgbox = QtWidgets.QMessageBox()
  3756. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3757. "\n"
  3758. "Do you want to Save the project?"))
  3759. msgbox.setWindowTitle(_("Save changes"))
  3760. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3761. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3762. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3763. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3764. msgbox.setDefaultButton(bt_yes)
  3765. msgbox.exec_()
  3766. response = msgbox.clickedButton()
  3767. if response == bt_yes:
  3768. self.trayIcon.hide()
  3769. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3770. elif response == bt_no:
  3771. self.trayIcon.hide()
  3772. self.quit_application()
  3773. elif response == bt_cancel:
  3774. return
  3775. else:
  3776. self.trayIcon.hide()
  3777. self.quit_application()
  3778. def quit_application(self):
  3779. """
  3780. Called (as a pyslot or not) when the application is quit.
  3781. :return: None
  3782. """
  3783. self.save_defaults()
  3784. log.debug("App.final_save() --> App Defaults saved.")
  3785. # save toolbar state to file
  3786. settings = QSettings("Open Source", "FlatCAM")
  3787. settings.setValue('saved_gui_state', self.ui.saveState())
  3788. settings.setValue('maximized_gui', self.ui.isMaximized())
  3789. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3790. settings.setValue('notebook_font_size',
  3791. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3792. settings.setValue('axis_font_size',
  3793. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3794. settings.setValue('textbox_font_size',
  3795. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value())
  3796. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3797. # This will write the setting to the platform specific storage.
  3798. del settings
  3799. log.debug("App.final_save() --> App UI state saved.")
  3800. QtWidgets.qApp.quit()
  3801. def on_portable_checked(self, state):
  3802. """
  3803. Callback called when the checkbox in Preferences GUI is checked.
  3804. It will set the application as portable by creating the preferences and recent files in the
  3805. 'config' folder found in the FlatCAM installation folder.
  3806. :param state: boolean, the state of the checkbox when clicked/checked
  3807. :return:
  3808. """
  3809. line_no = 0
  3810. data = None
  3811. if sys.platform != 'win32':
  3812. # this won't work in Linux or MacOS
  3813. return
  3814. # test if the app was frozen and choose the path for the configuration file
  3815. if getattr(sys, "frozen", False) is True:
  3816. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3817. else:
  3818. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3819. config_file = current_data_path + '\\configuration.txt'
  3820. try:
  3821. with open(config_file, 'r') as f:
  3822. try:
  3823. data = f.readlines()
  3824. except Exception as e:
  3825. log.debug('App.__init__() -->%s' % str(e))
  3826. return
  3827. except FileNotFoundError:
  3828. pass
  3829. for line in data:
  3830. line = line.strip('\n')
  3831. param = str(line).rpartition('=')
  3832. if param[0] == 'portable':
  3833. break
  3834. line_no += 1
  3835. if state:
  3836. data[line_no] = 'portable=True\n'
  3837. # create the new defauults files
  3838. # create current_defaults.FlatConfig file if there is none
  3839. try:
  3840. f = open(current_data_path + '/current_defaults.FlatConfig')
  3841. f.close()
  3842. except IOError:
  3843. App.log.debug('Creating empty current_defaults.FlatConfig')
  3844. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3845. json.dump({}, f)
  3846. f.close()
  3847. # create factory_defaults.FlatConfig file if there is none
  3848. try:
  3849. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3850. f.close()
  3851. except IOError:
  3852. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3853. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3854. json.dump({}, f)
  3855. f.close()
  3856. try:
  3857. f = open(current_data_path + '/recent.json')
  3858. f.close()
  3859. except IOError:
  3860. App.log.debug('Creating empty recent.json')
  3861. f = open(current_data_path + '/recent.json', 'w')
  3862. json.dump([], f)
  3863. f.close()
  3864. try:
  3865. fp = open(current_data_path + '/recent_projects.json')
  3866. fp.close()
  3867. except IOError:
  3868. App.log.debug('Creating empty recent_projects.json')
  3869. fp = open(current_data_path + '/recent_projects.json', 'w')
  3870. json.dump([], fp)
  3871. fp.close()
  3872. # save the current defaults to the new defaults file
  3873. self.save_defaults(silent=True, data_path=current_data_path)
  3874. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3875. else:
  3876. data[line_no] = 'portable=False\n'
  3877. with open(config_file, 'w') as f:
  3878. f.writelines(data)
  3879. def on_toggle_shell(self):
  3880. """
  3881. Toggle shell: if is visible close it, if it is closed then open it
  3882. :return:
  3883. """
  3884. self.report_usage("on_toggle_shell()")
  3885. if self.ui.shell_dock.isVisible():
  3886. self.ui.shell_dock.hide()
  3887. else:
  3888. self.ui.shell_dock.show()
  3889. def on_register_files(self, obj_type=None):
  3890. """
  3891. Called whenever there is a need to register file extensions with FlatCAM.
  3892. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3893. :param obj_type: the type of object to be register for.
  3894. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3895. :return: None
  3896. """
  3897. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3898. new_reg_path = 'Software\\Classes\\'
  3899. # find if the current user is admin
  3900. try:
  3901. is_admin = os.getuid() == 0
  3902. except AttributeError:
  3903. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3904. if is_admin is True:
  3905. root_path = winreg.HKEY_CLASSES_ROOT
  3906. else:
  3907. root_path = winreg.HKEY_CURRENT_USER
  3908. # create the keys
  3909. def set_reg(name, root_path, new_reg_path, value):
  3910. try:
  3911. winreg.CreateKey(root_path, new_reg_path)
  3912. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3913. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3914. return True
  3915. except WindowsError:
  3916. return False
  3917. # delete key in registry
  3918. def delete_reg(root_path, reg_path, key_to_del):
  3919. key_to_del_path = reg_path + key_to_del
  3920. try:
  3921. winreg.DeleteKey(root_path, key_to_del_path)
  3922. return True
  3923. except WindowsError:
  3924. return False
  3925. if obj_type is None or obj_type == 'excellon':
  3926. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3927. exc_list = [x for x in exc_list if x != '']
  3928. # register all keys in the Preferences window
  3929. for ext in exc_list:
  3930. new_k = new_reg_path + '.%s' % ext
  3931. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3932. # and unregister those that are no longer in the Preferences windows but are in the file
  3933. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3934. if ext not in exc_list:
  3935. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3936. # now write the updated extensions to the self.defaults
  3937. # new_ext = ''
  3938. # for ext in exc_list:
  3939. # new_ext = new_ext + ext + ', '
  3940. # self.defaults["fa_excellon"] = new_ext
  3941. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3942. if obj_type is None or obj_type == 'gcode':
  3943. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3944. gco_list = [x for x in gco_list if x != '']
  3945. # register all keys in the Preferences window
  3946. for ext in gco_list:
  3947. new_k = new_reg_path + '.%s' % ext
  3948. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3949. # and unregister those that are no longer in the Preferences windows but are in the file
  3950. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3951. if ext not in gco_list:
  3952. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3953. # now write the updated extensions to the self.defaults
  3954. # new_ext = ''
  3955. # for ext in gco_list:
  3956. # new_ext = new_ext + ext + ', '
  3957. # self.defaults["fa_gcode"] = new_ext
  3958. self.inform.emit('[success] %s' %
  3959. _("Selected GCode file extensions registered with FlatCAM."))
  3960. if obj_type is None or obj_type == 'gerber':
  3961. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3962. grb_list = [x for x in grb_list if x != '']
  3963. # register all keys in the Preferences window
  3964. for ext in grb_list:
  3965. new_k = new_reg_path + '.%s' % ext
  3966. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3967. # and unregister those that are no longer in the Preferences windows but are in the file
  3968. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3969. if ext not in grb_list:
  3970. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3971. # now write the updated extensions to the self.defaults
  3972. # new_ext = ''
  3973. # for ext in grb_list:
  3974. # new_ext = new_ext + ext + ', '
  3975. # self.defaults["fa_gerber"] = new_ext
  3976. self.inform.emit('[success] %s' %
  3977. _("Selected Gerber file extensions registered with FlatCAM."))
  3978. def add_extension(self, ext_type):
  3979. if ext_type == 'excellon':
  3980. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3981. if new_ext == '':
  3982. return
  3983. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3984. if new_ext in old_val:
  3985. return
  3986. old_val.append(new_ext)
  3987. old_val.sort()
  3988. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3989. if ext_type == 'gcode':
  3990. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3991. if new_ext == '':
  3992. return
  3993. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3994. if new_ext in old_val:
  3995. return
  3996. old_val.append(new_ext)
  3997. old_val.sort()
  3998. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3999. if ext_type == 'gerber':
  4000. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4001. if new_ext == '':
  4002. return
  4003. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4004. if new_ext in old_val:
  4005. return
  4006. old_val.append(new_ext)
  4007. old_val.sort()
  4008. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4009. if ext_type == 'keyword':
  4010. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4011. if new_kw == '':
  4012. return
  4013. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4014. if new_kw in old_val:
  4015. return
  4016. old_val.append(new_kw)
  4017. old_val.sort()
  4018. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4019. # update the self.myKeywords so the model is updated
  4020. self.autocomplete_kw_list = \
  4021. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4022. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4023. self.shell._edit.set_model_data(self.myKeywords)
  4024. self.ui.code_editor.set_model_data(self.myKeywords)
  4025. def del_extension(self, ext_type):
  4026. if ext_type == 'excellon':
  4027. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4028. if new_ext == '':
  4029. return
  4030. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4031. if new_ext not in old_val:
  4032. return
  4033. old_val.remove(new_ext)
  4034. old_val.sort()
  4035. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4036. if ext_type == 'gcode':
  4037. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4038. if new_ext == '':
  4039. return
  4040. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4041. if new_ext not in old_val:
  4042. return
  4043. old_val.remove(new_ext)
  4044. old_val.sort()
  4045. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4046. if ext_type == 'gerber':
  4047. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4048. if new_ext == '':
  4049. return
  4050. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4051. if new_ext not in old_val:
  4052. return
  4053. old_val.remove(new_ext)
  4054. old_val.sort()
  4055. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4056. if ext_type == 'keyword':
  4057. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4058. if new_kw == '':
  4059. return
  4060. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4061. if new_kw not in old_val:
  4062. return
  4063. old_val.remove(new_kw)
  4064. old_val.sort()
  4065. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4066. # update the self.myKeywords so the model is updated
  4067. self.autocomplete_kw_list = \
  4068. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4069. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4070. self.shell._edit.set_model_data(self.myKeywords)
  4071. self.ui.code_editor.set_model_data(self.myKeywords)
  4072. def restore_extensions(self, ext_type):
  4073. if ext_type == 'excellon':
  4074. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4075. # for the ability to open Excellon files with .txt extension
  4076. new_exc_list = deepcopy(self.exc_list)
  4077. try:
  4078. new_exc_list.remove('txt')
  4079. except ValueError:
  4080. pass
  4081. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4082. if ext_type == 'gcode':
  4083. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4084. if ext_type == 'gerber':
  4085. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4086. if ext_type == 'keyword':
  4087. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4088. # update the self.myKeywords so the model is updated
  4089. self.autocomplete_kw_list = self.default_keywords
  4090. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4091. self.shell._edit.set_model_data(self.myKeywords)
  4092. self.ui.code_editor.set_model_data(self.myKeywords)
  4093. def delete_all_extensions(self, ext_type):
  4094. if ext_type == 'excellon':
  4095. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4096. if ext_type == 'gcode':
  4097. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4098. if ext_type == 'gerber':
  4099. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4100. if ext_type == 'keyword':
  4101. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4102. # update the self.myKeywords so the model is updated
  4103. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4104. self.shell._edit.set_model_data(self.myKeywords)
  4105. self.ui.code_editor.set_model_data(self.myKeywords)
  4106. def on_edit_join(self, name=None):
  4107. """
  4108. Callback for Edit->Join. Joins the selected geometry objects into
  4109. a new one.
  4110. :return: None
  4111. """
  4112. self.report_usage("on_edit_join()")
  4113. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4114. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4115. tooldias = []
  4116. geo_type_list = set()
  4117. objs = self.collection.get_selected()
  4118. if len(objs) < 2:
  4119. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4120. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4121. return 'fail'
  4122. for obj in objs:
  4123. geo_type_list.add(obj.multigeo)
  4124. # if len(geo_type_list) == 1 means that all list elements are the same
  4125. if len(geo_type_list) != 1:
  4126. self.inform.emit('[ERROR] %s' %
  4127. _("Failed join. The Geometry objects are of different types.\n"
  4128. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4129. "convert from one to another and retry joining \n"
  4130. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4131. "the result may not be what was expected. \n"
  4132. "Check the generated GCODE."))
  4133. return
  4134. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4135. if True in geo_type_list:
  4136. def initialize(obj, app):
  4137. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4138. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4139. for v in obj.tools.values():
  4140. v['data']['name'] = obj_name_multi
  4141. self.new_object("geometry", obj_name_multi, initialize)
  4142. else:
  4143. def initialize(obj, app):
  4144. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4145. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4146. for v in obj.tools.values():
  4147. v['data']['name'] = obj_name_single
  4148. self.new_object("geometry", obj_name_single, initialize)
  4149. self.should_we_save = True
  4150. def on_edit_join_exc(self):
  4151. """
  4152. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4153. a new Excellon.
  4154. :return: None
  4155. """
  4156. self.report_usage("on_edit_join_exc()")
  4157. objs = self.collection.get_selected()
  4158. for obj in objs:
  4159. if not isinstance(obj, FlatCAMExcellon):
  4160. self.inform.emit('[ERROR_NOTCL] %s' %
  4161. _("Failed. Excellon joining works only on Excellon objects."))
  4162. return
  4163. if len(objs) < 2:
  4164. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4165. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4166. return 'fail'
  4167. def initialize(obj, app):
  4168. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4169. self.new_object("excellon", 'Combo_Excellon', initialize)
  4170. self.should_we_save = True
  4171. def on_edit_join_grb(self):
  4172. """
  4173. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4174. a new Gerber object.
  4175. :return: None
  4176. """
  4177. self.report_usage("on_edit_join_grb()")
  4178. objs = self.collection.get_selected()
  4179. for obj in objs:
  4180. if not isinstance(obj, FlatCAMGerber):
  4181. self.inform.emit('[ERROR_NOTCL] %s' %
  4182. _("Failed. Gerber joining works only on Gerber objects."))
  4183. return
  4184. if len(objs) < 2:
  4185. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4186. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4187. return 'fail'
  4188. def initialize(obj, app):
  4189. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4190. self.new_object("gerber", 'Combo_Gerber', initialize)
  4191. self.should_we_save = True
  4192. def on_convert_singlegeo_to_multigeo(self):
  4193. """
  4194. Called for converting a Geometry object from single-geo to multi-geo.
  4195. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4196. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4197. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4198. the solid-geometry of that tool.
  4199. :return: None
  4200. """
  4201. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4202. obj = self.collection.get_active()
  4203. if obj is None:
  4204. self.inform.emit('[ERROR_NOTCL] %s' %
  4205. _("Failed. Select a Geometry Object and try again."))
  4206. return
  4207. if not isinstance(obj, FlatCAMGeometry):
  4208. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4209. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4210. return
  4211. obj.multigeo = True
  4212. for tooluid, dict_value in obj.tools.items():
  4213. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4214. if not isinstance(obj.solid_geometry, list):
  4215. obj.solid_geometry = [obj.solid_geometry]
  4216. obj.solid_geometry[:] = []
  4217. obj.plot()
  4218. self.should_we_save = True
  4219. self.inform.emit('[success] %s' %
  4220. _("A Geometry object was converted to MultiGeo type."))
  4221. def on_convert_multigeo_to_singlegeo(self):
  4222. """
  4223. Called for converting a Geometry object from multi-geo to single-geo.
  4224. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4225. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4226. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4227. the solid-geometry of that tool.
  4228. :return: None
  4229. """
  4230. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4231. obj = self.collection.get_active()
  4232. if obj is None:
  4233. self.inform.emit('[ERROR_NOTCL] %s' %
  4234. _("Failed. Select a Geometry Object and try again."))
  4235. return
  4236. if not isinstance(obj, FlatCAMGeometry):
  4237. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4238. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4239. return
  4240. obj.multigeo = False
  4241. total_solid_geometry = []
  4242. for tooluid, dict_value in obj.tools.items():
  4243. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4244. # clear the original geometry
  4245. dict_value['solid_geometry'][:] = []
  4246. obj.solid_geometry = deepcopy(total_solid_geometry)
  4247. obj.plot()
  4248. self.should_we_save = True
  4249. self.inform.emit('[success] %s' %
  4250. _("A Geometry object was converted to SingleGeo type."))
  4251. def on_options_dict_change(self, field):
  4252. """
  4253. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4254. current project. This feature is no longer used.
  4255. :param field:
  4256. :return:
  4257. """
  4258. self.options_write_form_field(field)
  4259. if field == "units":
  4260. self.set_screen_units(self.options['units'])
  4261. def on_defaults_dict_change(self, field):
  4262. """
  4263. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4264. Edit -> Preferences tab window.
  4265. :param field: the key of the self.defaults dictionary that was changed.
  4266. :return: None
  4267. """
  4268. self.defaults_write_form_field(field)
  4269. if field == "units":
  4270. self.set_screen_units(self.defaults['units'])
  4271. def set_screen_units(self, units):
  4272. """
  4273. Set the FlatCAM units on the status bar.
  4274. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4275. :return: None
  4276. """
  4277. self.ui.units_label.setText("[" + units.lower() + "]")
  4278. def on_toggle_units(self, no_pref=False):
  4279. """
  4280. Callback for the Units radio-button change in the Preferences tab.
  4281. Changes the application's default units adn for the project too.
  4282. If changing the project's units, the change propagates to all of
  4283. the objects in the project.
  4284. :return: None
  4285. """
  4286. self.report_usage("on_toggle_units")
  4287. if self.toggle_units_ignore:
  4288. return
  4289. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4290. # If option is the same, then ignore
  4291. if new_units == self.defaults["units"].upper():
  4292. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4293. return
  4294. # Options to scale
  4295. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4296. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4297. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4298. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4299. "excellon_z_pdepth",
  4300. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4301. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4302. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4303. "geometry_feedrate_probe",
  4304. 'cncjob_tooldia',
  4305. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4306. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4307. "tools_2sided_drilldia", "tools_film_boundary",
  4308. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4309. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4310. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4311. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4312. "tools_transform_offset_y",
  4313. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4314. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4315. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4316. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4317. 'global_gridx', 'global_gridy', 'global_snap_max']
  4318. def scale_options(sfactor):
  4319. for dim in dimensions:
  4320. if dim == 'excellon_toolchangexy':
  4321. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4322. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4323. coords_xy[0] *= sfactor
  4324. coords_xy[1] *= sfactor
  4325. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4326. elif dim == 'geometry_toolchangexy':
  4327. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4328. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4329. coords_xy[0] *= sfactor
  4330. coords_xy[1] *= sfactor
  4331. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4332. elif dim == 'geometry_cnctooldia':
  4333. tools_diameters = []
  4334. try:
  4335. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4336. tools_diameters = [eval(a) for a in tools_string if a != '']
  4337. except Exception as e:
  4338. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4339. self.options['geometry_cnctooldia'] = ''
  4340. for t in range(len(tools_diameters)):
  4341. tools_diameters[t] *= sfactor
  4342. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4343. elif dim == 'tools_ncctools':
  4344. ncctools = []
  4345. try:
  4346. tools_string = self.defaults["tools_ncctools"].split(",")
  4347. ncctools = [eval(a) for a in tools_string if a != '']
  4348. except Exception as e:
  4349. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4350. self.options['tools_ncctools'] = ''
  4351. for t in range(len(ncctools)):
  4352. ncctools[t] *= sfactor
  4353. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4354. elif dim == 'tools_solderpaste_tools':
  4355. sptools = []
  4356. try:
  4357. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4358. sptools = [eval(a) for a in tools_string if a != '']
  4359. except Exception as e:
  4360. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4361. self.options['tools_solderpaste_tools'] = ""
  4362. for t in range(len(sptools)):
  4363. sptools[t] *= sfactor
  4364. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4365. elif dim == 'tools_solderpaste_xy_toolchange':
  4366. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4367. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4368. sp_coords[0] *= sfactor
  4369. sp_coords[1] *= sfactor
  4370. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4371. elif dim == 'global_gridx' or dim == 'global_gridy':
  4372. if new_units == 'IN':
  4373. val = 0.1
  4374. try:
  4375. val = float(self.defaults[dim]) * sfactor
  4376. except Exception as e:
  4377. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4378. self.options[dim] = float('%.6f' % val)
  4379. else:
  4380. val = 0.1
  4381. try:
  4382. val = float(self.defaults[dim]) * sfactor
  4383. except Exception as e:
  4384. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4385. self.options[dim] = float('%.4f' % val)
  4386. else:
  4387. val = 0.1
  4388. try:
  4389. val = float(self.options[dim]) * sfactor
  4390. except Exception as e:
  4391. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4392. self.options[dim] = val
  4393. def scale_defaults(sfactor):
  4394. for dim in dimensions:
  4395. if dim == 'excellon_toolchangexy':
  4396. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4397. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4398. coords_xy[0] *= sfactor
  4399. coords_xy[1] *= sfactor
  4400. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4401. elif dim == 'geometry_toolchangexy':
  4402. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4403. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4404. coords_xy[0] *= sfactor
  4405. coords_xy[1] *= sfactor
  4406. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4407. elif dim == 'geometry_cnctooldia':
  4408. tools_diameters = []
  4409. try:
  4410. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4411. tools_diameters = [eval(a) for a in tools_string if a != '']
  4412. except Exception as e:
  4413. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4414. self.defaults['geometry_cnctooldia'] = ''
  4415. for t in range(len(tools_diameters)):
  4416. tools_diameters[t] *= sfactor
  4417. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4418. elif dim == 'tools_ncctools':
  4419. ncctools = []
  4420. try:
  4421. tools_string = self.defaults["tools_ncctools"].split(",")
  4422. ncctools = [eval(a) for a in tools_string if a != '']
  4423. except Exception as e:
  4424. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4425. self.defaults['tools_ncctools'] = ''
  4426. for t in range(len(ncctools)):
  4427. ncctools[t] *= sfactor
  4428. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4429. elif dim == 'tools_solderpaste_tools':
  4430. sptools = []
  4431. try:
  4432. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4433. sptools = [eval(a) for a in tools_string if a != '']
  4434. except Exception as e:
  4435. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4436. self.defaults['tools_solderpaste_tools'] = ""
  4437. for t in range(len(sptools)):
  4438. sptools[t] *= sfactor
  4439. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4440. elif dim == 'tools_solderpaste_xy_toolchange':
  4441. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4442. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4443. sp_coords[0] *= sfactor
  4444. sp_coords[1] *= sfactor
  4445. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4446. elif dim == 'global_gridx' or dim == 'global_gridy':
  4447. if new_units == 'IN':
  4448. val = 0.1
  4449. try:
  4450. val = float(self.defaults[dim]) * sfactor
  4451. except Exception as e:
  4452. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4453. self.defaults[dim] = float('%.6f' % val)
  4454. else:
  4455. val = 0.1
  4456. try:
  4457. val = float(self.defaults[dim]) * sfactor
  4458. except Exception as e:
  4459. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4460. self.defaults[dim] = float('%.4f' % val)
  4461. else:
  4462. val = 0.1
  4463. try:
  4464. val = float(self.defaults[dim]) * sfactor
  4465. except Exception as e:
  4466. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4467. self.defaults[dim] = val
  4468. # The scaling factor depending on choice of units.
  4469. factor = 1/25.4
  4470. if new_units == 'MM':
  4471. factor = 25.4
  4472. # Changing project units. Warn user.
  4473. msgbox = QtWidgets.QMessageBox()
  4474. msgbox.setWindowTitle(_("Toggle Units"))
  4475. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4476. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4477. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4478. "properties of all objects to be scaled accordingly.\nContinue?"))
  4479. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4480. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4481. msgbox.setDefaultButton(bt_ok)
  4482. msgbox.exec_()
  4483. response = msgbox.clickedButton()
  4484. if response == bt_ok:
  4485. if no_pref is False:
  4486. self.options_read_form()
  4487. scale_options(factor)
  4488. self.options_write_form()
  4489. self.defaults_read_form()
  4490. scale_defaults(factor)
  4491. self.defaults_write_form(fl_units=new_units)
  4492. # save the defaults to file, some may assume that the conversion is enough and it's not
  4493. self.on_save_button()
  4494. self.should_we_save = True
  4495. # change this only if the workspace is active
  4496. if self.defaults['global_workspace'] is True:
  4497. self.plotcanvas.draw_workspace()
  4498. # adjust the grid values on the main toolbar
  4499. dec = 6 if new_units == 'IN'else 4
  4500. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4501. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4502. if not self.ui.grid_gap_link_cb.isChecked():
  4503. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4504. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4505. for obj in self.collection.get_list():
  4506. obj.convert_units(new_units)
  4507. # make that the properties stored in the object are also updated
  4508. self.object_changed.emit(obj)
  4509. obj.build_ui()
  4510. current = self.collection.get_active()
  4511. if current is not None:
  4512. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4513. if not isinstance(current, FlatCAMGeometry):
  4514. current.to_form()
  4515. self.plot_all()
  4516. self.inform.emit('[success] %s: %s' %
  4517. (_("Converted units to"), new_units))
  4518. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4519. self.set_screen_units(new_units)
  4520. else:
  4521. # Undo toggling
  4522. self.toggle_units_ignore = True
  4523. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4524. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4525. else:
  4526. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4527. self.toggle_units_ignore = False
  4528. self.inform.emit('[WARNING_NOTCL]%s' %
  4529. _(" Units conversion cancelled."))
  4530. self.options_read_form()
  4531. self.defaults_read_form()
  4532. def on_toggle_units_click(self):
  4533. try:
  4534. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4535. except (TypeError, AttributeError):
  4536. pass
  4537. if self.defaults["units"] == 'MM':
  4538. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4539. else:
  4540. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4541. self.on_toggle_units(no_pref=True)
  4542. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4543. lambda: self.on_toggle_units(no_pref=False))
  4544. def on_fullscreen(self):
  4545. self.report_usage("on_fullscreen()")
  4546. if self.toggle_fscreen is False:
  4547. if sys.platform == 'win32':
  4548. self.ui.showFullScreen()
  4549. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4550. tb.setVisible(False)
  4551. self.ui.splitter_left.setVisible(False)
  4552. self.toggle_fscreen = True
  4553. else:
  4554. if sys.platform == 'win32':
  4555. self.ui.showNormal()
  4556. self.restore_toolbar_view()
  4557. self.ui.splitter_left.setVisible(True)
  4558. self.toggle_fscreen = False
  4559. def on_toggle_plotarea(self):
  4560. self.report_usage("on_toggle_plotarea()")
  4561. try:
  4562. name = self.ui.plot_tab_area.widget(0).objectName()
  4563. except AttributeError:
  4564. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4565. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4566. self.ui.plot_tab_area.protectTab(0)
  4567. return
  4568. if name != 'plotarea':
  4569. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4570. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4571. self.ui.plot_tab_area.protectTab(0)
  4572. else:
  4573. self.ui.plot_tab_area.closeTab(0)
  4574. def on_toggle_notebook(self):
  4575. if self.ui.splitter.sizes()[0] == 0:
  4576. self.ui.splitter.setSizes([1, 1])
  4577. else:
  4578. self.ui.splitter.setSizes([0, 1])
  4579. def on_toggle_axis(self):
  4580. self.report_usage("on_toggle_axis()")
  4581. if self.toggle_axis is False:
  4582. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4583. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4584. self.plotcanvas.redraw()
  4585. self.toggle_axis = True
  4586. else:
  4587. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4588. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4589. self.plotcanvas.redraw()
  4590. self.toggle_axis = False
  4591. def on_toggle_grid(self):
  4592. self.report_usage("on_toggle_grid()")
  4593. self.ui.grid_snap_btn.trigger()
  4594. def on_options_combo_change(self, sel):
  4595. """
  4596. Called when the combo box to choose between application defaults and
  4597. project option changes value. The corresponding variables are
  4598. copied to the UI.
  4599. :param sel: The option index that was chosen.
  4600. :return: None
  4601. """
  4602. # combo_sel = self.ui.notebook.combo_options.get_active()
  4603. App.log.debug("Options --> %s" % sel)
  4604. # form = [self.defaults_form, self.options_form][sel]
  4605. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4606. if sel == 0:
  4607. self.gen_form = self.ui.general_defaults_form
  4608. self.ger_form = self.ui.gerber_defaults_form
  4609. self.exc_form = self.ui.excellon_defaults_form
  4610. self.geo_form = self.ui.geometry_defaults_form
  4611. self.cnc_form = self.ui.cncjob_defaults_form
  4612. self.tools_form = self.ui.tools_defaults_form
  4613. self.fa_form = self.ui.util_defaults_form
  4614. elif sel == 1:
  4615. self.gen_form = self.ui.general_options_form
  4616. self.ger_form = self.ui.gerber_options_form
  4617. self.exc_form = self.ui.excellon_options_form
  4618. self.geo_form = self.ui.geometry_options_form
  4619. self.cnc_form = self.ui.cncjob_options_form
  4620. self.tools_form = self.ui.tools_options_form
  4621. self.fa_form = self.ui.util_options_form
  4622. else:
  4623. return
  4624. try:
  4625. self.ui.general_scroll_area.takeWidget()
  4626. except:
  4627. self.log.debug("Nothing to remove")
  4628. self.ui.general_scroll_area.setWidget(self.gen_form)
  4629. self.gen_form.show()
  4630. try:
  4631. self.ui.gerber_scroll_area.takeWidget()
  4632. except:
  4633. self.log.debug("Nothing to remove")
  4634. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4635. self.ger_form.show()
  4636. try:
  4637. self.ui.excellon_scroll_area.takeWidget()
  4638. except:
  4639. self.log.debug("Nothing to remove")
  4640. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4641. self.exc_form.show()
  4642. try:
  4643. self.ui.geometry_scroll_area.takeWidget()
  4644. except:
  4645. self.log.debug("Nothing to remove")
  4646. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4647. self.geo_form.show()
  4648. try:
  4649. self.ui.cncjob_scroll_area.takeWidget()
  4650. except:
  4651. self.log.debug("Nothing to remove")
  4652. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4653. self.cnc_form.show()
  4654. try:
  4655. self.ui.tools_scroll_area.takeWidget()
  4656. except:
  4657. self.log.debug("Nothing to remove")
  4658. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4659. self.tools_form.show()
  4660. try:
  4661. self.ui.fa_scroll_area.takeWidget()
  4662. except:
  4663. self.log.debug("Nothing to remove")
  4664. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4665. self.fa_form.show()
  4666. self.log.debug("Finished GUI form initialization.")
  4667. # self.options2form()
  4668. def on_excellon_defaults_button(self):
  4669. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4670. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4671. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4672. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4673. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4674. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4675. log.debug("Excellon app defaults loaded ...")
  4676. def on_excellon_options_button(self):
  4677. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4678. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4679. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4680. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4681. self.options_form_fields["excellon_zeros"].set_value('L')
  4682. self.options_form_fields["excellon_units"].set_value('INCH')
  4683. log.debug("Excellon options defaults loaded ...")
  4684. def on_update_exc_export(self, state):
  4685. """
  4686. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4687. if the update_excellon_cb checkbox is checked
  4688. :param state: state of the checkbox whose signals is tied to his slot
  4689. :return:
  4690. """
  4691. if state:
  4692. # first try to disconnect
  4693. try:
  4694. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4695. disconnect(self.on_excellon_format_changed)
  4696. except TypeError:
  4697. pass
  4698. try:
  4699. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4700. disconnect(self.on_excellon_format_changed)
  4701. except TypeError:
  4702. pass
  4703. try:
  4704. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4705. disconnect(self.on_excellon_format_changed)
  4706. except TypeError:
  4707. pass
  4708. try:
  4709. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4710. disconnect(self.on_excellon_format_changed)
  4711. except TypeError:
  4712. pass
  4713. try:
  4714. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4715. disconnect(self.on_excellon_zeros_changed)
  4716. except TypeError:
  4717. pass
  4718. try:
  4719. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4720. disconnect(self.on_excellon_zeros_changed)
  4721. except TypeError:
  4722. pass
  4723. # the connect them
  4724. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4725. self.on_excellon_format_changed)
  4726. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4727. self.on_excellon_format_changed)
  4728. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4729. self.on_excellon_format_changed)
  4730. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4731. self.on_excellon_format_changed)
  4732. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4733. self.on_excellon_zeros_changed)
  4734. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4735. self.on_excellon_units_changed)
  4736. else:
  4737. # disconnect the signals
  4738. try:
  4739. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4740. disconnect(self.on_excellon_format_changed)
  4741. except TypeError:
  4742. pass
  4743. try:
  4744. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4745. disconnect(self.on_excellon_format_changed)
  4746. except TypeError:
  4747. pass
  4748. try:
  4749. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4750. disconnect(self.on_excellon_format_changed)
  4751. except TypeError:
  4752. pass
  4753. try:
  4754. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4755. disconnect(self.on_excellon_format_changed)
  4756. except TypeError:
  4757. pass
  4758. try:
  4759. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4760. disconnect(self.on_excellon_zeros_changed)
  4761. except TypeError:
  4762. pass
  4763. try:
  4764. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4765. disconnect(self.on_excellon_zeros_changed)
  4766. except TypeError:
  4767. pass
  4768. def on_excellon_format_changed(self):
  4769. """
  4770. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4771. :return: None
  4772. """
  4773. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4774. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4775. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4776. )
  4777. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4778. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4779. )
  4780. else:
  4781. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4782. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4783. )
  4784. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4785. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4786. )
  4787. def on_excellon_zeros_changed(self):
  4788. """
  4789. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4790. :return: None
  4791. """
  4792. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4793. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4794. )
  4795. def on_excellon_units_changed(self):
  4796. """
  4797. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4798. :return: None
  4799. """
  4800. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4801. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4802. )
  4803. self.on_excellon_format_changed()
  4804. # Setting plot colors handlers
  4805. def on_pf_color_entry(self):
  4806. self.defaults['global_plot_fill'] = \
  4807. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4808. self.defaults['global_plot_fill'][7:9]
  4809. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4810. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4811. def on_pf_color_button(self):
  4812. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4813. c_dialog = QtWidgets.QColorDialog()
  4814. plot_fill_color = c_dialog.getColor(initial=current_color)
  4815. if plot_fill_color.isValid() is False:
  4816. return
  4817. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4818. "background-color:%s" % str(plot_fill_color.name()))
  4819. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4820. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4821. self.defaults['global_plot_fill'] = new_val
  4822. def on_pf_color_spinner(self):
  4823. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4824. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4825. self.defaults['global_plot_fill'] = \
  4826. self.defaults['global_plot_fill'][:7] + \
  4827. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4828. self.defaults['global_plot_line'] = \
  4829. self.defaults['global_plot_line'][:7] + \
  4830. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4831. def on_pf_color_slider(self):
  4832. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4833. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4834. def on_pl_color_entry(self):
  4835. self.defaults['global_plot_line'] = \
  4836. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4837. self.defaults['global_plot_line'][7:9]
  4838. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4839. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4840. def on_pl_color_button(self):
  4841. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4842. # print(current_color)
  4843. c_dialog = QtWidgets.QColorDialog()
  4844. plot_line_color = c_dialog.getColor(initial=current_color)
  4845. if plot_line_color.isValid() is False:
  4846. return
  4847. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4848. "background-color:%s" % str(plot_line_color.name()))
  4849. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4850. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4851. self.defaults['global_plot_line'] = new_val_line
  4852. # Setting selection colors (left - right) handlers
  4853. def on_sf_color_entry(self):
  4854. self.defaults['global_sel_fill'] = \
  4855. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4856. self.defaults['global_sel_fill'][7:9]
  4857. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4858. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4859. def on_sf_color_button(self):
  4860. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4861. c_dialog = QtWidgets.QColorDialog()
  4862. plot_fill_color = c_dialog.getColor(initial=current_color)
  4863. if plot_fill_color.isValid() is False:
  4864. return
  4865. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4866. "background-color:%s" % str(plot_fill_color.name()))
  4867. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4868. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4869. self.defaults['global_sel_fill'] = new_val
  4870. def on_sf_color_spinner(self):
  4871. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4872. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4873. self.defaults['global_sel_fill'] = \
  4874. self.defaults['global_sel_fill'][:7] + \
  4875. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4876. self.defaults['global_sel_line'] = \
  4877. self.defaults['global_sel_line'][:7] + \
  4878. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4879. def on_sf_color_slider(self):
  4880. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4881. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4882. def on_sl_color_entry(self):
  4883. self.defaults['global_sel_line'] = \
  4884. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4885. self.defaults['global_sel_line'][7:9]
  4886. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4887. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4888. def on_sl_color_button(self):
  4889. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4890. c_dialog = QtWidgets.QColorDialog()
  4891. plot_line_color = c_dialog.getColor(initial=current_color)
  4892. if plot_line_color.isValid() is False:
  4893. return
  4894. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4895. "background-color:%s" % str(plot_line_color.name()))
  4896. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4897. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4898. self.defaults['global_sel_line'] = new_val_line
  4899. # Setting selection colors (right - left) handlers
  4900. def on_alt_sf_color_entry(self):
  4901. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4902. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4903. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4904. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4905. def on_alt_sf_color_button(self):
  4906. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4907. c_dialog = QtWidgets.QColorDialog()
  4908. plot_fill_color = c_dialog.getColor(initial=current_color)
  4909. if plot_fill_color.isValid() is False:
  4910. return
  4911. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4912. "background-color:%s" % str(plot_fill_color.name()))
  4913. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4914. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4915. self.defaults['global_alt_sel_fill'] = new_val
  4916. def on_alt_sf_color_spinner(self):
  4917. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4918. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4919. self.defaults['global_alt_sel_fill'] = \
  4920. self.defaults['global_alt_sel_fill'][:7] + \
  4921. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4922. self.defaults['global_alt_sel_line'] = \
  4923. self.defaults['global_alt_sel_line'][:7] + \
  4924. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4925. def on_alt_sf_color_slider(self):
  4926. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4927. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4928. def on_alt_sl_color_entry(self):
  4929. self.defaults['global_alt_sel_line'] = \
  4930. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4931. self.defaults['global_alt_sel_line'][7:9]
  4932. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4933. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4934. def on_alt_sl_color_button(self):
  4935. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4936. c_dialog = QtWidgets.QColorDialog()
  4937. plot_line_color = c_dialog.getColor(initial=current_color)
  4938. if plot_line_color.isValid() is False:
  4939. return
  4940. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4941. "background-color:%s" % str(plot_line_color.name()))
  4942. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4943. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4944. self.defaults['global_alt_sel_line'] = new_val_line
  4945. # Setting Editor colors
  4946. def on_draw_color_entry(self):
  4947. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4948. .draw_color_entry.get_value()
  4949. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4950. "background-color:%s" % str(self.defaults['global_draw_color']))
  4951. def on_draw_color_button(self):
  4952. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4953. c_dialog = QtWidgets.QColorDialog()
  4954. draw_color = c_dialog.getColor(initial=current_color)
  4955. if draw_color.isValid() is False:
  4956. return
  4957. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4958. "background-color:%s" % str(draw_color.name()))
  4959. new_val = str(draw_color.name())
  4960. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4961. self.defaults['global_draw_color'] = new_val
  4962. def on_sel_draw_color_entry(self):
  4963. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4964. .sel_draw_color_entry.get_value()
  4965. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4966. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4967. def on_sel_draw_color_button(self):
  4968. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4969. c_dialog = QtWidgets.QColorDialog()
  4970. sel_draw_color = c_dialog.getColor(initial=current_color)
  4971. if sel_draw_color.isValid() is False:
  4972. return
  4973. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4974. "background-color:%s" % str(sel_draw_color.name()))
  4975. new_val_sel = str(sel_draw_color.name())
  4976. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4977. self.defaults['global_sel_draw_color'] = new_val_sel
  4978. def on_proj_color_entry(self):
  4979. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4980. .proj_color_entry.get_value()
  4981. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4982. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4983. def on_proj_color_button(self):
  4984. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4985. c_dialog = QtWidgets.QColorDialog()
  4986. proj_color = c_dialog.getColor(initial=current_color)
  4987. if proj_color.isValid() is False:
  4988. return
  4989. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4990. "background-color:%s" % str(proj_color.name()))
  4991. new_val_sel = str(proj_color.name())
  4992. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4993. self.defaults['global_proj_item_color'] = new_val_sel
  4994. def on_proj_color_dis_entry(self):
  4995. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4996. .proj_color_dis_entry.get_value()
  4997. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4998. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4999. def on_proj_color_dis_button(self):
  5000. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5001. c_dialog = QtWidgets.QColorDialog()
  5002. proj_color = c_dialog.getColor(initial=current_color)
  5003. if proj_color.isValid() is False:
  5004. return
  5005. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5006. "background-color:%s" % str(proj_color.name()))
  5007. new_val_sel = str(proj_color.name())
  5008. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5009. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5010. def on_annotation_fontcolor_entry(self):
  5011. self.defaults['cncjob_annotation_fontcolor'] = \
  5012. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5013. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5014. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5015. def on_annotation_fontcolor_button(self):
  5016. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5017. c_dialog = QtWidgets.QColorDialog()
  5018. annotation_color = c_dialog.getColor(initial=current_color)
  5019. if annotation_color.isValid() is False:
  5020. return
  5021. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5022. "background-color:%s" % str(annotation_color.name()))
  5023. new_val_sel = str(annotation_color.name())
  5024. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5025. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5026. def on_film_color_entry(self):
  5027. self.defaults['tools_film_color'] = \
  5028. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5029. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5030. "background-color:%s" % str(self.defaults['tools_film_color']))
  5031. def on_film_color_button(self):
  5032. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5033. c_dialog = QtWidgets.QColorDialog()
  5034. film_color = c_dialog.getColor(initial=current_color)
  5035. if film_color.isValid() is False:
  5036. return
  5037. # if new color is different then mark that the Preferences are changed
  5038. if film_color != current_color:
  5039. self.on_preferences_edited()
  5040. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5041. "background-color:%s" % str(film_color.name()))
  5042. new_val_sel = str(film_color.name())
  5043. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5044. self.defaults['tools_film_color'] = new_val_sel
  5045. def on_splash_changed(self, state):
  5046. settings = QSettings("Open Source", "FlatCAM")
  5047. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5048. # This will write the setting to the platform specific storage.
  5049. del settings
  5050. def on_notebook_tab_rmb_click(self, checked):
  5051. self.ui.notebook.set_detachable(val=checked)
  5052. self.defaults["global_tabs_detachable"] = checked
  5053. self.ui.plot_tab_area.set_detachable(val=checked)
  5054. self.defaults["global_tabs_detachable"] = checked
  5055. def on_deselect_all(self):
  5056. self.collection.set_all_inactive()
  5057. self.delete_selection_shape()
  5058. def on_workspace_modified(self):
  5059. self.save_defaults(silent=True)
  5060. self.plotcanvas.draw_workspace()
  5061. def on_workspace(self):
  5062. self.report_usage("on_workspace()")
  5063. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5064. self.plotcanvas.restore_workspace()
  5065. else:
  5066. self.plotcanvas.delete_workspace()
  5067. self.save_defaults(silent=True)
  5068. def on_workspace_menu(self):
  5069. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5070. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5071. else:
  5072. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5073. self.on_workspace()
  5074. def on_layout(self, index=None, lay=None):
  5075. self.report_usage("on_layout()")
  5076. if lay:
  5077. current_layout = lay
  5078. else:
  5079. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5080. settings = QSettings("Open Source", "FlatCAM")
  5081. settings.setValue('layout', current_layout)
  5082. # This will write the setting to the platform specific storage.
  5083. del settings
  5084. # first remove the toolbars:
  5085. try:
  5086. self.ui.removeToolBar(self.ui.toolbarfile)
  5087. self.ui.removeToolBar(self.ui.toolbargeo)
  5088. self.ui.removeToolBar(self.ui.toolbarview)
  5089. self.ui.removeToolBar(self.ui.toolbarshell)
  5090. self.ui.removeToolBar(self.ui.toolbartools)
  5091. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5092. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5093. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5094. self.ui.removeToolBar(self.ui.snap_toolbar)
  5095. self.ui.removeToolBar(self.ui.toolbarshell)
  5096. except Exception as e:
  5097. pass
  5098. if current_layout == 'standard':
  5099. # ## TOOLBAR INSTALLATION # ##
  5100. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5101. self.ui.toolbarfile.setObjectName('File_TB')
  5102. self.ui.addToolBar(self.ui.toolbarfile)
  5103. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5104. self.ui.toolbargeo.setObjectName('Edit_TB')
  5105. self.ui.addToolBar(self.ui.toolbargeo)
  5106. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5107. self.ui.toolbarview.setObjectName('View_TB')
  5108. self.ui.addToolBar(self.ui.toolbarview)
  5109. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5110. self.ui.toolbarshell.setObjectName('Shell_TB')
  5111. self.ui.addToolBar(self.ui.toolbarshell)
  5112. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5113. self.ui.toolbartools.setObjectName('Tools_TB')
  5114. self.ui.addToolBar(self.ui.toolbartools)
  5115. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5116. # self.ui.exc_edit_toolbar.setVisible(False)
  5117. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5118. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5119. self.ui.addToolBarBreak()
  5120. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5121. # self.ui.geo_edit_toolbar.setVisible(False)
  5122. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5123. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5124. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5125. # self.ui.grb_edit_toolbar.setVisible(False)
  5126. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5127. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5128. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5129. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5130. # self.ui.snap_toolbar.setMaximumHeight(30)
  5131. self.ui.addToolBar(self.ui.snap_toolbar)
  5132. self.ui.corner_snap_btn.setVisible(False)
  5133. self.ui.snap_magnet.setVisible(False)
  5134. elif current_layout == 'compact':
  5135. # ## TOOLBAR INSTALLATION # ##
  5136. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5137. self.ui.toolbarfile.setObjectName('File_TB')
  5138. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5139. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5140. self.ui.toolbargeo.setObjectName('Edit_TB')
  5141. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5142. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5143. self.ui.toolbarshell.setObjectName('Shell_TB')
  5144. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5145. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5146. self.ui.toolbartools.setObjectName('Tools_TB')
  5147. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5148. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5149. # self.ui.geo_edit_toolbar.setVisible(False)
  5150. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5151. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5152. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5153. self.ui.toolbarview.setObjectName('View_TB')
  5154. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5155. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5156. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5157. # self.ui.grb_edit_toolbar.setVisible(False)
  5158. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5159. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5160. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5161. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5162. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5163. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5164. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5165. self.ui.snap_toolbar.setMaximumHeight(30)
  5166. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5167. self.ui.corner_snap_btn.setVisible(True)
  5168. self.ui.snap_magnet.setVisible(True)
  5169. # add all the actions to the toolbars
  5170. self.ui.populate_toolbars()
  5171. # reconnect all the signals to the toolbar actions
  5172. self.connect_toolbar_signals()
  5173. self.ui.grid_snap_btn.setChecked(True)
  5174. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5175. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5176. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5177. self.ui.grid_gap_link_cb.setChecked(True)
  5178. def on_cnc_custom_parameters(self, signal_text):
  5179. if signal_text == 'Parameters':
  5180. return
  5181. else:
  5182. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5183. def on_save_button(self):
  5184. log.debug("App.on_save_button() --> Saving preferences to file.")
  5185. self.preferences_changed_flag = False
  5186. self.save_defaults(silent=False)
  5187. # load the defaults so they are updated into the app
  5188. self.load_defaults(filename='current_defaults')
  5189. # Re-fresh project options
  5190. self.on_options_app2project()
  5191. settings = QSettings("Open Source", "FlatCAM")
  5192. # save the notebook font size
  5193. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5194. settings.setValue('notebook_font_size', fsize)
  5195. # save the axis font size
  5196. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5197. settings.setValue('axis_font_size', g_fsize)
  5198. # save the textbox font size
  5199. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5200. settings.setValue('textbox_font_size', tb_fsize)
  5201. # This will write the setting to the platform specific storage.
  5202. del settings
  5203. def handlePrint(self):
  5204. self.report_usage("handlePrint()")
  5205. dialog = QtPrintSupport.QPrintDialog()
  5206. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5207. self.ui.code_editor.document().print_(dialog.printer())
  5208. def handlePreview(self):
  5209. self.report_usage("handlePreview()")
  5210. dialog = QtPrintSupport.QPrintPreviewDialog()
  5211. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5212. dialog.exec_()
  5213. def handleTextChanged(self):
  5214. # enable = not self.ui.code_editor.document().isEmpty()
  5215. # self.ui.buttonPrint.setEnabled(enable)
  5216. # self.ui.buttonPreview.setEnabled(enable)
  5217. pass
  5218. def handleOpen(self, filt=None):
  5219. self.report_usage("handleOpen()")
  5220. if filt:
  5221. _filter_ = filt
  5222. else:
  5223. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5224. "All Files (*.*)"
  5225. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5226. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5227. if path:
  5228. file = QtCore.QFile(path)
  5229. if file.open(QtCore.QIODevice.ReadOnly):
  5230. stream = QtCore.QTextStream(file)
  5231. self.gcode_edited = stream.readAll()
  5232. self.ui.code_editor.setPlainText(self.gcode_edited)
  5233. file.close()
  5234. def handleSaveGCode(self, name=None, filt=None):
  5235. self.report_usage("handleSaveGCode()")
  5236. if filt:
  5237. _filter_ = filt
  5238. else:
  5239. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5240. "All Files (*.*)"
  5241. if name:
  5242. obj_name = name
  5243. else:
  5244. try:
  5245. obj_name = self.collection.get_active().options['name']
  5246. except AttributeError:
  5247. obj_name = 'file'
  5248. if filt is None:
  5249. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5250. try:
  5251. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5252. caption=_("Export G-Code ..."),
  5253. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5254. filter=_filter_
  5255. )[0])
  5256. except TypeError:
  5257. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5258. if filename == "":
  5259. self.inform.emit('[WARNING_NOTCL] %s' %
  5260. _("Export Code cancelled."))
  5261. return
  5262. else:
  5263. try:
  5264. my_gcode = self.ui.code_editor.toPlainText()
  5265. with open(filename, 'w') as f:
  5266. for line in my_gcode:
  5267. f.write(line)
  5268. except FileNotFoundError:
  5269. self.inform.emit('[WARNING] %s' %
  5270. _("No such file or directory"))
  5271. return
  5272. except PermissionError:
  5273. self.inform.emit('[WARNING] %s' %
  5274. _("Permission denied, saving not possible.\n"
  5275. "Most likely another app is holding the file open and not accessible."))
  5276. return
  5277. # Just for adding it to the recent files list.
  5278. if self.defaults["global_open_style"] is False:
  5279. self.file_opened.emit("cncjob", filename)
  5280. self.file_saved.emit("cncjob", filename)
  5281. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5282. def handleFindGCode(self):
  5283. self.report_usage("handleFindGCode()")
  5284. flags = QtGui.QTextDocument.FindCaseSensitively
  5285. text_to_be_found = self.ui.entryFind.get_value()
  5286. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5287. if r is False:
  5288. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5289. def handleReplaceGCode(self):
  5290. self.report_usage("handleReplaceGCode()")
  5291. old = self.ui.entryFind.get_value()
  5292. new = self.ui.entryReplace.get_value()
  5293. if self.ui.sel_all_cb.isChecked():
  5294. while True:
  5295. cursor = self.ui.code_editor.textCursor()
  5296. cursor.beginEditBlock()
  5297. flags = QtGui.QTextDocument.FindCaseSensitively
  5298. # self.ui.editor is the QPlainTextEdit
  5299. r = self.ui.code_editor.find(str(old), flags)
  5300. if r:
  5301. qc = self.ui.code_editor.textCursor()
  5302. if qc.hasSelection():
  5303. qc.insertText(new)
  5304. else:
  5305. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5306. break
  5307. # Mark end of undo block
  5308. cursor.endEditBlock()
  5309. else:
  5310. cursor = self.ui.code_editor.textCursor()
  5311. cursor.beginEditBlock()
  5312. qc = self.ui.code_editor.textCursor()
  5313. if qc.hasSelection():
  5314. qc.insertText(new)
  5315. # Mark end of undo block
  5316. cursor.endEditBlock()
  5317. def handleRunCode(self):
  5318. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5319. # tries to print on a hidden widget, therefore show the dock if hidden
  5320. if self.ui.shell_dock.isHidden():
  5321. self.ui.shell_dock.show()
  5322. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5323. # self.shell._sysShell.exec_command(script_code)
  5324. old_line = ''
  5325. for tcl_command_line in self.script_code.splitlines():
  5326. # do not process lines starting with '#' = comment and empty lines
  5327. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5328. # id FlatCAM is run in Windows then replace all the slashes with
  5329. # the UNIX style slash that TCL understands
  5330. if sys.platform == 'win32':
  5331. if "open" in tcl_command_line:
  5332. tcl_command_line = tcl_command_line.replace('\\', '/')
  5333. if old_line != '':
  5334. new_command = old_line + tcl_command_line + '\n'
  5335. else:
  5336. new_command = tcl_command_line
  5337. # execute the actual Tcl command
  5338. try:
  5339. self.shell.open_proccessing() # Disables input box.
  5340. result = self.tcl.eval(str(new_command))
  5341. if result != 'None':
  5342. self.shell.append_output(result + '\n')
  5343. old_line = ''
  5344. except tk.TclError:
  5345. old_line = old_line + tcl_command_line + '\n'
  5346. except Exception as e:
  5347. log.debug("App.handleRunCode() --> %s" % str(e))
  5348. if old_line != '':
  5349. # it means that the script finished with an error
  5350. result = self.tcl.eval("set errorInfo")
  5351. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5352. self.shell.append_error('ERROR: ' + result + '\n')
  5353. self.shell.close_proccessing()
  5354. def on_tool_add_keypress(self):
  5355. # ## Current application units in Upper Case
  5356. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5357. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5358. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5359. if notebook_widget_name == 'selected_tab':
  5360. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5361. # Tool add works for Geometry only if Advanced is True in Preferences
  5362. if self.defaults["global_app_level"] == 'a':
  5363. tool_add_popup = FCInputDialog(title="New Tool ...",
  5364. text='Enter a Tool Diameter:',
  5365. min=0.0000, max=99.9999, decimals=4)
  5366. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5367. val, ok = tool_add_popup.get_value()
  5368. if ok:
  5369. if float(val) == 0:
  5370. self.inform.emit('[WARNING_NOTCL] %s' %
  5371. _("Please enter a tool diameter with non-zero value, in Float format."))
  5372. return
  5373. self.collection.get_active().on_tool_add(dia=float(val))
  5374. else:
  5375. self.inform.emit('[WARNING_NOTCL] %s...' %
  5376. _("Adding Tool cancelled"))
  5377. else:
  5378. msgbox = QtWidgets.QMessageBox()
  5379. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5380. "Go to Preferences -> General - Show Advanced Options."))
  5381. msgbox.setWindowTitle("Tool adding ...")
  5382. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5383. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5384. msgbox.setDefaultButton(bt_ok)
  5385. msgbox.exec_()
  5386. # work only if the notebook tab on focus is the Tools_Tab
  5387. if notebook_widget_name == 'tool_tab':
  5388. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5389. tool_add_popup = FCInputDialog(title="New Tool ...",
  5390. text='Enter a Tool Diameter:',
  5391. min=0.0000, max=99.9999, decimals=4)
  5392. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5393. val, ok = tool_add_popup.get_value()
  5394. # and only if the tool is NCC Tool
  5395. if tool_widget == self.ncclear_tool.toolName:
  5396. if ok:
  5397. if float(val) == 0:
  5398. self.inform.emit('[WARNING_NOTCL] %s' %
  5399. _("Please enter a tool diameter with non-zero value, in Float format."))
  5400. return
  5401. self.ncclear_tool.on_tool_add(dia=float(val))
  5402. else:
  5403. self.inform.emit('[WARNING_NOTCL] %s...' %
  5404. _("Adding Tool cancelled"))
  5405. # and only if the tool is Paint Area Tool
  5406. elif tool_widget == self.paint_tool.toolName:
  5407. if ok:
  5408. if float(val) == 0:
  5409. self.inform.emit('[WARNING_NOTCL] %s' %
  5410. _("Please enter a tool diameter with non-zero value, in Float format."))
  5411. return
  5412. self.paint_tool.on_tool_add(dia=float(val))
  5413. else:
  5414. self.inform.emit('[WARNING_NOTCL] %s...' %
  5415. _("Adding Tool cancelled"))
  5416. # and only if the tool is Solder Paste Dispensing Tool
  5417. elif tool_widget == self.paste_tool.toolName:
  5418. if ok:
  5419. if float(val) == 0:
  5420. self.inform.emit('[WARNING_NOTCL] %s' %
  5421. _("Please enter a tool diameter with non-zero value, in Float format."))
  5422. return
  5423. self.paste_tool.on_tool_add(dia=float(val))
  5424. else:
  5425. self.inform.emit('[WARNING_NOTCL] %s...' %
  5426. _("Adding Tool cancelled"))
  5427. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5428. # See description bellow.
  5429. def on_delete_keypress(self):
  5430. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5431. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5432. if notebook_widget_name == 'selected_tab':
  5433. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5434. self.collection.get_active().on_tool_delete()
  5435. # work only if the notebook tab on focus is the Tools_Tab
  5436. elif notebook_widget_name == 'tool_tab':
  5437. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5438. # and only if the tool is NCC Tool
  5439. if tool_widget == self.ncclear_tool.toolName:
  5440. self.ncclear_tool.on_tool_delete()
  5441. # and only if the tool is Paint Tool
  5442. elif tool_widget == self.paint_tool.toolName:
  5443. self.paint_tool.on_tool_delete()
  5444. # and only if the tool is Solder Paste Dispensing Tool
  5445. elif tool_widget == self.paste_tool.toolName:
  5446. self.paste_tool.on_tool_delete()
  5447. else:
  5448. self.on_delete()
  5449. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5450. # some screens you have to be careful where you hover with your mouse.
  5451. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5452. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5453. # Complicated, I know :)
  5454. def on_delete(self):
  5455. """
  5456. Delete the currently selected FlatCAMObjs.
  5457. :return: None
  5458. """
  5459. self.report_usage("on_delete()")
  5460. response = None
  5461. bt_ok = None
  5462. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5463. # a geometry object before we update it.
  5464. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5465. and self.grb_editor.editor_active is False:
  5466. if self.defaults["global_delete_confirmation"] is True:
  5467. msgbox = QtWidgets.QMessageBox()
  5468. msgbox.setWindowTitle(_("Delete objects"))
  5469. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5470. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5471. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5472. "the selected objects?"))
  5473. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5474. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5475. msgbox.setDefaultButton(bt_ok)
  5476. msgbox.exec_()
  5477. response = msgbox.clickedButton()
  5478. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5479. if self.collection.get_active():
  5480. self.log.debug("App.on_delete()")
  5481. while self.collection.get_active():
  5482. obj_active = self.collection.get_active()
  5483. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5484. if isinstance(obj_active, FlatCAMGerber):
  5485. for el in obj_active.mark_shapes:
  5486. obj_active.mark_shapes[el].clear(update=True)
  5487. obj_active.mark_shapes[el].enabled = False
  5488. # obj_active.mark_shapes[el] = None
  5489. del el
  5490. elif isinstance(obj_active, FlatCAMCNCjob):
  5491. try:
  5492. obj_active.annotation.clear(update=True)
  5493. obj_active.annotation.enabled = False
  5494. except AttributeError:
  5495. pass
  5496. self.delete_first_selected()
  5497. self.inform.emit('%s...' %
  5498. _("Object(s) deleted"))
  5499. # make sure that the selection shape is deleted, too
  5500. self.delete_selection_shape()
  5501. else:
  5502. self.inform.emit(_("Failed. No object(s) selected..."))
  5503. else:
  5504. self.inform.emit(_("Save the work in Editor and try again ..."))
  5505. def delete_first_selected(self):
  5506. # Keep this for later
  5507. try:
  5508. sel_obj = self.collection.get_active()
  5509. name = sel_obj.options["name"]
  5510. except AttributeError:
  5511. self.log.debug("Nothing selected for deletion")
  5512. return
  5513. # Remove from dictionary
  5514. self.collection.delete_active()
  5515. # Clear form
  5516. self.setup_component_editor()
  5517. self.inform.emit('%s: %s' %
  5518. (_("Object deleted"), name))
  5519. def on_set_origin(self):
  5520. """
  5521. Set the origin to the left mouse click position
  5522. :return: None
  5523. """
  5524. # display the message for the user
  5525. # and ask him to click on the desired position
  5526. self.report_usage("on_set_origin()")
  5527. def origin_replot():
  5528. def worker_task():
  5529. with self.proc_container.new('%s...' % _("Plotting")):
  5530. for obj in self.collection.get_list():
  5531. obj.plot()
  5532. self.plotcanvas.fit_view()
  5533. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  5534. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5535. self.inform.emit(_('Click to set the origin ...'))
  5536. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  5537. # first disconnect it as it may have been used by something else
  5538. try:
  5539. self.replot_signal.disconnect()
  5540. except TypeError:
  5541. pass
  5542. self.replot_signal[list].connect(origin_replot)
  5543. def on_set_zero_click(self, event):
  5544. # this function will be available only for mouse left click
  5545. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5546. if event.button == 1:
  5547. if self.grid_status() == True:
  5548. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5549. else:
  5550. pos = pos_canvas
  5551. x = 0 - pos[0]
  5552. y = 0 - pos[1]
  5553. def worker_task():
  5554. with self.proc_container.new(_("Setting Origin...")):
  5555. for obj in self.collection.get_list():
  5556. obj.offset((x, y))
  5557. self.object_changed.emit(obj)
  5558. # Update the object bounding box options
  5559. a, b, c, d = obj.bounds()
  5560. obj.options['xmin'] = a
  5561. obj.options['ymin'] = b
  5562. obj.options['xmax'] = c
  5563. obj.options['ymax'] = d
  5564. self.inform.emit('[success]%s...' %
  5565. _('Origin set'))
  5566. self.replot_signal.emit([])
  5567. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5568. self.should_we_save = True
  5569. def on_jump_to(self, custom_location=None, fit_center=True):
  5570. """
  5571. Jump to a location by setting the mouse cursor location
  5572. :return:
  5573. """
  5574. self.report_usage("on_jump_to()")
  5575. if not custom_location:
  5576. dia_box = Dialog_box(title=_("Jump to ..."),
  5577. label=_("Enter the coordinates in format X,Y:"),
  5578. icon=QtGui.QIcon('share/jump_to16.png'))
  5579. if dia_box.ok is True:
  5580. try:
  5581. location = eval(dia_box.location)
  5582. if not isinstance(location, tuple):
  5583. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5584. return
  5585. except:
  5586. return
  5587. else:
  5588. return
  5589. else:
  5590. location = custom_location
  5591. if fit_center:
  5592. self.plotcanvas.fit_center(loc=location)
  5593. cursor = QtGui.QCursor()
  5594. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5595. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5596. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5597. self.inform.emit('[success] %s' %
  5598. _("Done."))
  5599. return location
  5600. def on_copy_object(self):
  5601. self.report_usage("on_copy_object()")
  5602. def initialize(obj_init, app):
  5603. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5604. try:
  5605. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5606. except AttributeError:
  5607. pass
  5608. try:
  5609. obj_init.apertures = deepcopy(obj.apertures)
  5610. except AttributeError:
  5611. pass
  5612. try:
  5613. if obj.tools:
  5614. obj_init.tools = deepcopy(obj.tools)
  5615. except Exception as e:
  5616. log.debug("App.on_copy_object() --> %s" % str(e))
  5617. def initialize_excellon(obj_init, app):
  5618. obj_init.tools = deepcopy(obj.tools)
  5619. # drills are offset, so they need to be deep copied
  5620. obj_init.drills = deepcopy(obj.drills)
  5621. # slots are offset, so they need to be deep copied
  5622. obj_init.slots = deepcopy(obj.slots)
  5623. obj_init.create_geometry()
  5624. for obj in self.collection.get_selected():
  5625. obj_name = obj.options["name"]
  5626. try:
  5627. if isinstance(obj, FlatCAMExcellon):
  5628. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5629. elif isinstance(obj, FlatCAMGerber):
  5630. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5631. elif isinstance(obj, FlatCAMGeometry):
  5632. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5633. except Exception as e:
  5634. return "Operation failed: %s" % str(e)
  5635. def on_copy_object2(self, custom_name):
  5636. def initialize_geometry(obj_init, app):
  5637. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5638. try:
  5639. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5640. except AttributeError:
  5641. pass
  5642. try:
  5643. obj_init.apertures = deepcopy(obj.apertures)
  5644. except AttributeError:
  5645. pass
  5646. try:
  5647. if obj.tools:
  5648. obj_init.tools = deepcopy(obj.tools)
  5649. except Exception as e:
  5650. log.debug("on_copy_object2() --> %s" % str(e))
  5651. def initialize_gerber(obj_init, app):
  5652. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5653. obj_init.apertures = deepcopy(obj.apertures)
  5654. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5655. def initialize_excellon(obj_init, app):
  5656. obj_init.tools = deepcopy(obj.tools)
  5657. # drills are offset, so they need to be deep copied
  5658. obj_init.drills = deepcopy(obj.drills)
  5659. # slots are offset, so they need to be deep copied
  5660. obj_init.slots = deepcopy(obj.slots)
  5661. obj_init.create_geometry()
  5662. for obj in self.collection.get_selected():
  5663. obj_name = obj.options["name"]
  5664. try:
  5665. if isinstance(obj, FlatCAMExcellon):
  5666. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5667. elif isinstance(obj, FlatCAMGerber):
  5668. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5669. elif isinstance(obj, FlatCAMGeometry):
  5670. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5671. except Exception as e:
  5672. return "Operation failed: %s" % str(e)
  5673. def on_rename_object(self, text):
  5674. self.report_usage("on_rename_object()")
  5675. named_obj = self.collection.get_active()
  5676. for obj in named_obj:
  5677. if obj is list:
  5678. self.on_rename_object(text)
  5679. else:
  5680. try:
  5681. obj.options['name'] = text
  5682. except Exception as e:
  5683. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5684. def convert_any2geo(self):
  5685. self.report_usage("convert_any2geo()")
  5686. def initialize(obj_init, app):
  5687. obj_init.solid_geometry = obj.solid_geometry
  5688. try:
  5689. obj_init.follow_geometry = obj.follow_geometry
  5690. except AttributeError:
  5691. pass
  5692. try:
  5693. obj_init.apertures = obj.apertures
  5694. except AttributeError:
  5695. pass
  5696. try:
  5697. if obj.tools:
  5698. obj_init.tools = obj.tools
  5699. except AttributeError:
  5700. pass
  5701. def initialize_excellon(obj_init, app):
  5702. # objs = self.collection.get_selected()
  5703. # FlatCAMGeometry.merge(objs, obj)
  5704. solid_geo = []
  5705. for tool in obj.tools:
  5706. for geo in obj.tools[tool]['solid_geometry']:
  5707. solid_geo.append(geo)
  5708. obj_init.solid_geometry = deepcopy(solid_geo)
  5709. if not self.collection.get_selected():
  5710. log.warning("App.convert_any2geo --> No object selected")
  5711. self.inform.emit('[WARNING_NOTCL] %s' %
  5712. _("No object is selected. Select an object and try again."))
  5713. return
  5714. for obj in self.collection.get_selected():
  5715. obj_name = obj.options["name"]
  5716. try:
  5717. if isinstance(obj, FlatCAMExcellon):
  5718. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5719. else:
  5720. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5721. except Exception as e:
  5722. return "Operation failed: %s" % str(e)
  5723. def convert_any2gerber(self):
  5724. self.report_usage("convert_any2gerber()")
  5725. def initialize_geometry(obj_init, app):
  5726. apertures = {}
  5727. apid = 0
  5728. apertures[str(apid)] = {}
  5729. apertures[str(apid)]['geometry'] = []
  5730. for obj_orig in obj.solid_geometry:
  5731. new_elem = dict()
  5732. new_elem['solid'] = obj_orig
  5733. new_elem['follow'] = obj_orig.exterior
  5734. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5735. apertures[str(apid)]['size'] = 0.0
  5736. apertures[str(apid)]['type'] = 'C'
  5737. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5738. obj_init.apertures = deepcopy(apertures)
  5739. def initialize_excellon(obj_init, app):
  5740. apertures = {}
  5741. apid = 10
  5742. for tool in obj.tools:
  5743. apertures[str(apid)] = {}
  5744. apertures[str(apid)]['geometry'] = []
  5745. for geo in obj.tools[tool]['solid_geometry']:
  5746. new_el = dict()
  5747. new_el['solid'] = geo
  5748. new_el['follow'] = geo.exterior
  5749. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5750. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5751. apertures[str(apid)]['type'] = 'C'
  5752. apid += 1
  5753. # create solid_geometry
  5754. solid_geometry = []
  5755. for apid in apertures:
  5756. for geo_el in apertures[apid]['geometry']:
  5757. solid_geometry.append(geo_el['solid'])
  5758. solid_geometry = MultiPolygon(solid_geometry)
  5759. solid_geometry = solid_geometry.buffer(0.0000001)
  5760. obj_init.solid_geometry = deepcopy(solid_geometry)
  5761. obj_init.apertures = deepcopy(apertures)
  5762. # clear the working objects (perhaps not necessary due of Python GC)
  5763. apertures.clear()
  5764. if not self.collection.get_selected():
  5765. log.warning("App.convert_any2gerber --> No object selected")
  5766. self.inform.emit('[WARNING_NOTCL] %s' %
  5767. _("No object is selected. Select an object and try again."))
  5768. return
  5769. for obj in self.collection.get_selected():
  5770. obj_name = obj.options["name"]
  5771. try:
  5772. if isinstance(obj, FlatCAMExcellon):
  5773. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5774. elif isinstance(obj, FlatCAMGeometry):
  5775. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5776. else:
  5777. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5778. except Exception as e:
  5779. return "Operation failed: %s" % str(e)
  5780. def abort_all_tasks(self):
  5781. if self.abort_flag is False:
  5782. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5783. self.abort_flag = True
  5784. def app_is_idle(self):
  5785. if self.abort_flag:
  5786. self.inform.emit('[WARNING_NOTCL] %s' %
  5787. _("The current task was gracefully closed on user request..."))
  5788. self.abort_flag = False
  5789. def on_selectall(self):
  5790. self.report_usage("on_selectall()")
  5791. # delete the possible selection box around a possible selected object
  5792. self.delete_selection_shape()
  5793. for name in self.collection.get_names():
  5794. self.collection.set_active(name)
  5795. curr_sel_obj = self.collection.get_by_name(name)
  5796. # create the selection box around the selected object
  5797. if self.defaults['global_selection_shape'] is True:
  5798. self.draw_selection_shape(curr_sel_obj)
  5799. def on_preferences(self):
  5800. # add the tab if it was closed
  5801. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5802. # delete the absolute and relative position and messages in the infobar
  5803. self.ui.position_label.setText("")
  5804. self.ui.rel_position_label.setText("")
  5805. # Switch plot_area to preferences page
  5806. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5807. # self.ui.show()
  5808. # this disconnect() is done so the slot will be connected only once
  5809. try:
  5810. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5811. except (TypeError, AttributeError):
  5812. pass
  5813. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5814. # detect changes in the preferences
  5815. for idx in range(self.ui.pref_tab_area.count()):
  5816. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5817. try:
  5818. try:
  5819. tb.textEdited.disconnect(self.on_preferences_edited)
  5820. except (TypeError, AttributeError):
  5821. pass
  5822. tb.textEdited.connect(self.on_preferences_edited)
  5823. except AttributeError:
  5824. pass
  5825. try:
  5826. try:
  5827. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5828. except (TypeError, AttributeError):
  5829. pass
  5830. tb.modificationChanged.connect(self.on_preferences_edited)
  5831. except AttributeError:
  5832. pass
  5833. try:
  5834. try:
  5835. tb.toggled.disconnect(self.on_preferences_edited)
  5836. except (TypeError, AttributeError):
  5837. pass
  5838. tb.toggled.connect(self.on_preferences_edited)
  5839. except AttributeError:
  5840. pass
  5841. try:
  5842. try:
  5843. tb.valueChanged.disconnect(self.on_preferences_edited)
  5844. except (TypeError, AttributeError):
  5845. pass
  5846. tb.valueChanged.connect(self.on_preferences_edited)
  5847. except AttributeError:
  5848. pass
  5849. try:
  5850. try:
  5851. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5852. except (TypeError, AttributeError):
  5853. pass
  5854. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5855. except AttributeError:
  5856. pass
  5857. def on_preferences_edited(self):
  5858. self.inform.emit('[WARNING_NOTCL] %s' %
  5859. _("Preferences edited but not saved."))
  5860. self.preferences_changed_flag = True
  5861. def on_preferences_closed(self):
  5862. # disconnect
  5863. for idx in range(self.ui.pref_tab_area.count()):
  5864. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5865. try:
  5866. tb.textEdited.disconnect(self.on_preferences_edited)
  5867. except (TypeError, AttributeError):
  5868. pass
  5869. try:
  5870. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5871. except (TypeError, AttributeError):
  5872. pass
  5873. try:
  5874. tb.toggled.disconnect(self.on_preferences_edited)
  5875. except (TypeError, AttributeError):
  5876. pass
  5877. try:
  5878. tb.valueChanged.disconnect(self.on_preferences_edited)
  5879. except (TypeError, AttributeError):
  5880. pass
  5881. try:
  5882. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5883. except (TypeError, AttributeError):
  5884. pass
  5885. if self.preferences_changed_flag is True:
  5886. msgbox = QtWidgets.QMessageBox()
  5887. msgbox.setText(_("One or more values are changed.\n"
  5888. "Do you want to save the Preferences?"))
  5889. msgbox.setWindowTitle(_("Save Preferences"))
  5890. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5891. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5892. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5893. msgbox.setDefaultButton(bt_yes)
  5894. msgbox.exec_()
  5895. response = msgbox.clickedButton()
  5896. if response == bt_yes:
  5897. self.on_save_button()
  5898. self.inform.emit('[success] %s' %
  5899. _("Preferences saved."))
  5900. else:
  5901. self.preferences_changed_flag = False
  5902. return
  5903. def on_flipy(self):
  5904. self.report_usage("on_flipy()")
  5905. obj_list = self.collection.get_selected()
  5906. xminlist = []
  5907. yminlist = []
  5908. xmaxlist = []
  5909. ymaxlist = []
  5910. if not obj_list:
  5911. self.inform.emit('[WARNING_NOTCL] %s' %
  5912. _("No object selected to Flip on Y axis."))
  5913. else:
  5914. try:
  5915. # first get a bounding box to fit all
  5916. for obj in obj_list:
  5917. xmin, ymin, xmax, ymax = obj.bounds()
  5918. xminlist.append(xmin)
  5919. yminlist.append(ymin)
  5920. xmaxlist.append(xmax)
  5921. ymaxlist.append(ymax)
  5922. # get the minimum x,y and maximum x,y for all objects selected
  5923. xminimal = min(xminlist)
  5924. yminimal = min(yminlist)
  5925. xmaximal = max(xmaxlist)
  5926. ymaximal = max(ymaxlist)
  5927. px = 0.5 * (xminimal + xmaximal)
  5928. py = 0.5 * (yminimal + ymaximal)
  5929. # execute mirroring
  5930. for obj in obj_list:
  5931. obj.mirror('X', [px, py])
  5932. obj.plot()
  5933. self.object_changed.emit(obj)
  5934. self.inform.emit('[success] %s' %
  5935. _("Flip on Y axis done."))
  5936. except Exception as e:
  5937. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5938. (_("Flip action was not executed."), str(e)))
  5939. return
  5940. def on_flipx(self):
  5941. self.report_usage("on_flipx()")
  5942. obj_list = self.collection.get_selected()
  5943. xminlist = []
  5944. yminlist = []
  5945. xmaxlist = []
  5946. ymaxlist = []
  5947. if not obj_list:
  5948. self.inform.emit('[WARNING_NOTCL] %s' %
  5949. _("No object selected to Flip on X axis."))
  5950. else:
  5951. try:
  5952. # first get a bounding box to fit all
  5953. for obj in obj_list:
  5954. xmin, ymin, xmax, ymax = obj.bounds()
  5955. xminlist.append(xmin)
  5956. yminlist.append(ymin)
  5957. xmaxlist.append(xmax)
  5958. ymaxlist.append(ymax)
  5959. # get the minimum x,y and maximum x,y for all objects selected
  5960. xminimal = min(xminlist)
  5961. yminimal = min(yminlist)
  5962. xmaximal = max(xmaxlist)
  5963. ymaximal = max(ymaxlist)
  5964. px = 0.5 * (xminimal + xmaximal)
  5965. py = 0.5 * (yminimal + ymaximal)
  5966. # execute mirroring
  5967. for obj in obj_list:
  5968. obj.mirror('Y', [px, py])
  5969. obj.plot()
  5970. self.object_changed.emit(obj)
  5971. self.inform.emit('[success] %s' %
  5972. _("Flip on X axis done."))
  5973. except Exception as e:
  5974. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5975. (_("Flip action was not executed."), str(e)))
  5976. return
  5977. def on_rotate(self, silent=False, preset=None):
  5978. self.report_usage("on_rotate()")
  5979. obj_list = self.collection.get_selected()
  5980. xminlist = []
  5981. yminlist = []
  5982. xmaxlist = []
  5983. ymaxlist = []
  5984. if not obj_list:
  5985. self.inform.emit('[WARNING_NOTCL] %s' %
  5986. _("No object selected to Rotate."))
  5987. else:
  5988. if silent is False:
  5989. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5990. min=-360, max=360, decimals=4,
  5991. init_val=float(self.defaults['tools_transform_rotate']))
  5992. num, ok = rotatebox.get_value()
  5993. else:
  5994. num = preset
  5995. ok = True
  5996. if ok:
  5997. try:
  5998. # first get a bounding box to fit all
  5999. for obj in obj_list:
  6000. xmin, ymin, xmax, ymax = obj.bounds()
  6001. xminlist.append(xmin)
  6002. yminlist.append(ymin)
  6003. xmaxlist.append(xmax)
  6004. ymaxlist.append(ymax)
  6005. # get the minimum x,y and maximum x,y for all objects selected
  6006. xminimal = min(xminlist)
  6007. yminimal = min(yminlist)
  6008. xmaximal = max(xmaxlist)
  6009. ymaximal = max(ymaxlist)
  6010. px = 0.5 * (xminimal + xmaximal)
  6011. py = 0.5 * (yminimal + ymaximal)
  6012. for sel_obj in obj_list:
  6013. sel_obj.rotate(-float(num), point=(px, py))
  6014. sel_obj.plot()
  6015. self.object_changed.emit(sel_obj)
  6016. self.inform.emit('[success] %s' %
  6017. _("Rotation done."))
  6018. except Exception as e:
  6019. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6020. (_("Rotation movement was not executed."), str(e)))
  6021. return
  6022. def on_skewx(self):
  6023. self.report_usage("on_skewx()")
  6024. obj_list = self.collection.get_selected()
  6025. xminlist = []
  6026. yminlist = []
  6027. if not obj_list:
  6028. self.inform.emit('[WARNING_NOTCL] %s' %
  6029. _("No object selected to Skew/Shear on X axis."))
  6030. else:
  6031. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6032. min=-360, max=360, decimals=4,
  6033. init_val=float(self.defaults['tools_transform_skew_x']))
  6034. num, ok = skewxbox.get_value()
  6035. if ok:
  6036. # first get a bounding box to fit all
  6037. for obj in obj_list:
  6038. xmin, ymin, xmax, ymax = obj.bounds()
  6039. xminlist.append(xmin)
  6040. yminlist.append(ymin)
  6041. # get the minimum x,y and maximum x,y for all objects selected
  6042. xminimal = min(xminlist)
  6043. yminimal = min(yminlist)
  6044. for obj in obj_list:
  6045. obj.skew(num, 0, point=(xminimal, yminimal))
  6046. obj.plot()
  6047. self.object_changed.emit(obj)
  6048. self.inform.emit('[success] %s' %
  6049. _("Skew on X axis done."))
  6050. def on_skewy(self):
  6051. self.report_usage("on_skewy()")
  6052. obj_list = self.collection.get_selected()
  6053. xminlist = []
  6054. yminlist = []
  6055. if not obj_list:
  6056. self.inform.emit('[WARNING_NOTCL] %s' %
  6057. _("No object selected to Skew/Shear on Y axis."))
  6058. else:
  6059. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6060. min=-360, max=360, decimals=4,
  6061. init_val=float(self.defaults['tools_transform_skew_y']))
  6062. num, ok = skewybox.get_value()
  6063. if ok:
  6064. # first get a bounding box to fit all
  6065. for obj in obj_list:
  6066. xmin, ymin, xmax, ymax = obj.bounds()
  6067. xminlist.append(xmin)
  6068. yminlist.append(ymin)
  6069. # get the minimum x,y and maximum x,y for all objects selected
  6070. xminimal = min(xminlist)
  6071. yminimal = min(yminlist)
  6072. for obj in obj_list:
  6073. obj.skew(0, num, point=(xminimal, yminimal))
  6074. obj.plot()
  6075. self.object_changed.emit(obj)
  6076. self.inform.emit('[success] %s' %
  6077. _("Skew on Y axis done."))
  6078. def on_plots_updated(self):
  6079. """
  6080. Callback used to report when the plots have changed.
  6081. Adjust axes and zooms to fit.
  6082. :return: None
  6083. """
  6084. self.plotcanvas.update() # TODO: Need update canvas?
  6085. self.on_zoom_fit(None)
  6086. self.collection.update_view()
  6087. # self.inform.emit(_("Plots updated ..."))
  6088. # TODO: Rework toolbar 'clear', 'replot' functions
  6089. def on_toolbar_replot(self):
  6090. """
  6091. Callback for toolbar button. Re-plots all objects.
  6092. :return: None
  6093. """
  6094. self.report_usage("on_toolbar_replot")
  6095. self.log.debug("on_toolbar_replot()")
  6096. try:
  6097. self.collection.get_active().read_form()
  6098. except AttributeError:
  6099. self.log.debug("on_toolbar_replot(): AttributeError")
  6100. pass
  6101. self.plot_all()
  6102. def on_row_activated(self, index):
  6103. if index.isValid():
  6104. if index.internalPointer().parent_item != self.collection.root_item:
  6105. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6106. self.collection.on_item_activated(index)
  6107. def grid_status(self):
  6108. if self.ui.grid_snap_btn.isChecked():
  6109. return True
  6110. else:
  6111. return False
  6112. def populate_cmenu_grids(self):
  6113. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6114. self.ui.cmenu_gridmenu.clear()
  6115. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6116. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6117. grid_toggle.setCheckable(True)
  6118. if self.grid_status() == True:
  6119. grid_toggle.setChecked(True)
  6120. else:
  6121. grid_toggle.setChecked(False)
  6122. self.ui.cmenu_gridmenu.addSeparator()
  6123. for grid in sorted_list:
  6124. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6125. action.triggered.connect(self.set_grid)
  6126. self.ui.cmenu_gridmenu.addSeparator()
  6127. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6128. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6129. grid_add.triggered.connect(self.on_grid_add)
  6130. grid_delete.triggered.connect(self.on_grid_delete)
  6131. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6132. def set_grid(self):
  6133. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6134. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6135. def on_grid_add(self):
  6136. # ## Current application units in lower Case
  6137. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6138. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6139. text=_('Enter a Grid Value:'),
  6140. min=0.0000, max=99.9999, decimals=4)
  6141. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6142. val, ok = grid_add_popup.get_value()
  6143. if ok:
  6144. if float(val) == 0:
  6145. self.inform.emit('[WARNING_NOTCL] %s' %
  6146. _("Please enter a grid value with non-zero value, in Float format."))
  6147. return
  6148. else:
  6149. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6150. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6151. self.inform.emit('[success] %s...' %
  6152. _("New Grid added"))
  6153. else:
  6154. self.inform.emit('[WARNING_NOTCL] %s...' %
  6155. _("Grid already exists"))
  6156. else:
  6157. self.inform.emit('[WARNING_NOTCL] %s...' %
  6158. _("Adding New Grid cancelled"))
  6159. def on_grid_delete(self):
  6160. # ## Current application units in lower Case
  6161. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6162. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6163. text='Enter a Grid Value:',
  6164. min=0.0000, max=99.9999, decimals=4)
  6165. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6166. val, ok = grid_del_popup.get_value()
  6167. if ok:
  6168. if float(val) == 0:
  6169. self.inform.emit('[WARNING_NOTCL] %s' %
  6170. _("Please enter a grid value with non-zero value, in Float format."))
  6171. return
  6172. else:
  6173. try:
  6174. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6175. except ValueError:
  6176. self.inform.emit('[ERROR_NOTCL]%s...' %
  6177. _(" Grid Value does not exist"))
  6178. return
  6179. self.inform.emit('[success] %s...' %
  6180. _("Grid Value deleted"))
  6181. else:
  6182. self.inform.emit('[WARNING_NOTCL] %s...' %
  6183. _("Delete Grid value cancelled"))
  6184. def on_shortcut_list(self):
  6185. self.report_usage("on_shortcut_list()")
  6186. # add the tab if it was closed
  6187. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6188. # delete the absolute and relative position and messages in the infobar
  6189. self.ui.position_label.setText("")
  6190. self.ui.rel_position_label.setText("")
  6191. # Switch plot_area to preferences page
  6192. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6193. # self.ui.show()
  6194. def on_select_tab(self, name):
  6195. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6196. if self.ui.splitter.sizes()[0] == 0:
  6197. self.ui.splitter.setSizes([1, 1])
  6198. else:
  6199. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6200. self.ui.splitter.setSizes([0, 1])
  6201. if name == 'project':
  6202. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6203. elif name == 'selected':
  6204. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6205. elif name == 'tool':
  6206. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6207. def on_copy_name(self):
  6208. self.report_usage("on_copy_name()")
  6209. obj = self.collection.get_active()
  6210. try:
  6211. name = obj.options["name"]
  6212. except AttributeError:
  6213. log.debug("on_copy_name() --> No object selected to copy it's name")
  6214. self.inform.emit('[WARNING_NOTCL]%s' %
  6215. _(" No object selected to copy it's name"))
  6216. return
  6217. self.clipboard.setText(name)
  6218. self.inform.emit(_("Name copied on clipboard ..."))
  6219. def on_mouse_click_over_plot(self, event):
  6220. """
  6221. Default actions are:
  6222. :param event: Contains information about the event, like which button
  6223. was clicked, the pixel coordinates and the axes coordinates.
  6224. :return: None
  6225. """
  6226. self.pos = []
  6227. # So it can receive key presses
  6228. self.plotcanvas.native.setFocus()
  6229. # Set the mouse button for panning
  6230. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  6231. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6232. if self.grid_status() == True:
  6233. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6234. self.app_cursor.enabled = True
  6235. else:
  6236. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6237. self.app_cursor.enabled = False
  6238. try:
  6239. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6240. if event.button == 1:
  6241. # Reset here the relative coordinates so there is a new reference on the click position
  6242. if self.rel_point1 is None:
  6243. self.rel_point1 = self.pos
  6244. else:
  6245. self.rel_point2 = copy(self.rel_point1)
  6246. self.rel_point1 = self.pos
  6247. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6248. if modifiers == QtCore.Qt.ShiftModifier:
  6249. # do not auto open the Project Tab
  6250. self.click_noproject = True
  6251. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6252. self.inform.emit('[success] %s' %
  6253. _("Coordinates copied to clipboard."))
  6254. return
  6255. self.on_mouse_move_over_plot(event, origin_click=True)
  6256. except Exception as e:
  6257. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6258. def on_double_click_over_plot(self, event):
  6259. self.doubleclick = True
  6260. def on_mouse_move_over_plot(self, event, origin_click=None):
  6261. """
  6262. Callback for the mouse motion event over the plot.
  6263. :param event: Contains information about the event.
  6264. :param origin_click
  6265. :return: None
  6266. """
  6267. # So it can receive key presses
  6268. self.plotcanvas.native.setFocus()
  6269. self.pos_jump = event.pos
  6270. self.ui.popMenu.mouse_is_panning = False
  6271. if not origin_click:
  6272. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6273. if event.button == 2 and event.is_dragging == 1:
  6274. self.ui.popMenu.mouse_is_panning = True
  6275. return
  6276. if self.rel_point1 is not None:
  6277. try: # May fail in case mouse not within axes
  6278. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6279. if self.grid_status() == True:
  6280. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6281. self.app_cursor.enabled = True
  6282. # Update cursor
  6283. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  6284. else:
  6285. pos = (pos_canvas[0], pos_canvas[1])
  6286. self.app_cursor.enabled = False
  6287. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6288. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6289. dx = pos[0] - self.rel_point1[0]
  6290. dy = pos[1] - self.rel_point1[1]
  6291. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6292. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6293. self.mouse = [pos[0], pos[1]]
  6294. # if the mouse is moved and the LMB is clicked then the action is a selection
  6295. if event.is_dragging == 1 and event.button == 1:
  6296. self.delete_selection_shape()
  6297. if dx < 0:
  6298. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6299. face_color=self.defaults['global_alt_sel_fill'])
  6300. self.selection_type = False
  6301. else:
  6302. self.draw_moving_selection_shape(self.pos, pos)
  6303. self.selection_type = True
  6304. # hover effect - enabled in Preferences -> General -> GUI Settings
  6305. if self.defaults['global_hover']:
  6306. for obj in self.collection.get_list():
  6307. try:
  6308. # select the object(s) only if it is enabled (plotted)
  6309. if obj.options['plot']:
  6310. if obj not in self.collection.get_selected():
  6311. poly_obj = Polygon(
  6312. [(obj.options['xmin'], obj.options['ymin']),
  6313. (obj.options['xmax'], obj.options['ymin']),
  6314. (obj.options['xmax'], obj.options['ymax']),
  6315. (obj.options['xmin'], obj.options['ymax'])]
  6316. )
  6317. if Point(pos).within(poly_obj):
  6318. if obj.isHovering is False:
  6319. obj.isHovering = True
  6320. obj.notHovering = True
  6321. # create the selection box around the selected object
  6322. self.draw_hover_shape(obj, color='#d1e0e0')
  6323. else:
  6324. if obj.notHovering is True:
  6325. obj.notHovering = False
  6326. obj.isHovering = False
  6327. self.delete_hover_shape()
  6328. except:
  6329. # the Exception here will happen if we try to select on screen and we have an
  6330. # newly (and empty) just created Geometry or Excellon object that do not have the
  6331. # xmin, xmax, ymin, ymax options.
  6332. # In this case poly_obj creation (see above) will fail
  6333. pass
  6334. except:
  6335. self.ui.position_label.setText("")
  6336. self.ui.rel_position_label.setText("")
  6337. self.mouse = None
  6338. def on_mouse_click_release_over_plot(self, event):
  6339. """
  6340. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6341. and has been registered in ''self.__init__()''.
  6342. :param event: contains information about the event.
  6343. :return:
  6344. """
  6345. pos = 0, 0
  6346. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6347. if self.grid_status() == True:
  6348. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6349. else:
  6350. pos = (pos_canvas[0], pos_canvas[1])
  6351. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6352. # canvas menu
  6353. if event.button == 2: # right click
  6354. if self.ui.popMenu.mouse_is_panning is False:
  6355. self.cursor = QtGui.QCursor()
  6356. self.populate_cmenu_grids()
  6357. self.ui.popMenu.popup(self.cursor.pos())
  6358. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6359. # selection and then select a type of selection ("enclosing" or "touching")
  6360. try:
  6361. if event.button == 1: # left click
  6362. if self.doubleclick is True:
  6363. self.doubleclick = False
  6364. if self.collection.get_selected():
  6365. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6366. if self.ui.splitter.sizes()[0] == 0:
  6367. self.ui.splitter.setSizes([1, 1])
  6368. # delete the selection shape(S) as it may be in the way
  6369. self.delete_selection_shape()
  6370. self.delete_hover_shape()
  6371. else:
  6372. if self.selection_type is not None:
  6373. self.selection_area_handler(self.pos, pos, self.selection_type)
  6374. self.selection_type = None
  6375. else:
  6376. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6377. if key_modifier == QtCore.Qt.ShiftModifier:
  6378. mod_key = 'Shift'
  6379. elif key_modifier == QtCore.Qt.ControlModifier:
  6380. mod_key = 'Control'
  6381. else:
  6382. mod_key = None
  6383. if mod_key == self.defaults["global_mselect_key"]:
  6384. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6385. # deselect, and if it's not selected then it will be selected
  6386. # If there is no active command (self.command_active is None) then we check if we clicked
  6387. # on a object by checking the bounding limits against mouse click position
  6388. if self.command_active is None:
  6389. self.select_objects(key='CTRL')
  6390. self.delete_hover_shape()
  6391. else:
  6392. # If there is no active command (self.command_active is None) then we check if we clicked
  6393. # on a object by checking the bounding limits against mouse click position
  6394. if self.command_active is None:
  6395. self.select_objects()
  6396. self.delete_hover_shape()
  6397. except Exception as e:
  6398. log.warning("Error: %s" % str(e))
  6399. return
  6400. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6401. """
  6402. :param start_pos: mouse position when the selection LMB click was done
  6403. :param end_pos: mouse position when the left mouse button is released
  6404. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6405. :return:
  6406. """
  6407. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6408. self.delete_selection_shape()
  6409. for obj in self.collection.get_list():
  6410. try:
  6411. # select the object(s) only if it is enabled (plotted)
  6412. if obj.options['plot']:
  6413. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6414. (obj.options['xmax'], obj.options['ymin']),
  6415. (obj.options['xmax'], obj.options['ymax']),
  6416. (obj.options['xmin'], obj.options['ymax'])])
  6417. if sel_type is True:
  6418. if poly_obj.within(poly_selection):
  6419. # create the selection box around the selected object
  6420. if self.defaults['global_selection_shape'] is True:
  6421. self.draw_selection_shape(obj)
  6422. self.collection.set_active(obj.options['name'])
  6423. else:
  6424. if poly_selection.intersects(poly_obj):
  6425. # create the selection box around the selected object
  6426. if self.defaults['global_selection_shape'] is True:
  6427. self.draw_selection_shape(obj)
  6428. self.collection.set_active(obj.options['name'])
  6429. except Exception as e:
  6430. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6431. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6432. # In this case poly_obj creation (see above) will fail
  6433. log.debug("App.selection_area_handler() --> %s" % str(e))
  6434. def select_objects(self, key=None):
  6435. # list where we store the overlapped objects under our mouse left click position
  6436. objects_under_the_click_list = []
  6437. # Populate the list with the overlapped objects on the click position
  6438. curr_x, curr_y = self.pos
  6439. for obj in self.all_objects_list:
  6440. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6441. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6442. if obj.options['name'] not in objects_under_the_click_list:
  6443. if obj.options['plot']:
  6444. # add objects to the objects_under_the_click list only if the object is plotted
  6445. # (active and not disabled)
  6446. objects_under_the_click_list.append(obj.options['name'])
  6447. try:
  6448. # If there is no element in the overlapped objects list then make everyone inactive
  6449. # because we selected "nothing"
  6450. if not objects_under_the_click_list:
  6451. self.collection.set_all_inactive()
  6452. # delete the possible selection box around a possible selected object
  6453. self.delete_selection_shape()
  6454. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6455. # only when working on App
  6456. if self.call_source == 'app':
  6457. if self.click_noproject is False:
  6458. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6459. else:
  6460. # restore auto open the Project Tab
  6461. self.click_noproject = False
  6462. # delete any text in the status bar, implicitly the last object name that was selected
  6463. self.inform.emit("")
  6464. else:
  6465. self.call_source = 'app'
  6466. else:
  6467. # case when there is only an object under the click and we toggle it
  6468. if len(objects_under_the_click_list) == 1:
  6469. if self.collection.get_active() is None:
  6470. self.collection.set_active(objects_under_the_click_list[0])
  6471. # create the selection box around the selected object
  6472. curr_sel_obj = self.collection.get_active()
  6473. if self.defaults['global_selection_shape'] is True:
  6474. self.draw_selection_shape(curr_sel_obj)
  6475. # self.inform.emit('[selected] %s: %s selected' %
  6476. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6477. if curr_sel_obj.kind == 'gerber':
  6478. self.inform.emit(
  6479. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6480. color='green', name=str(curr_sel_obj.options['name'])))
  6481. elif curr_sel_obj.kind == 'excellon':
  6482. self.inform.emit(
  6483. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6484. color='brown', name=str(curr_sel_obj.options['name'])))
  6485. elif curr_sel_obj.kind == 'cncjob':
  6486. self.inform.emit(
  6487. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6488. color='blue', name=str(curr_sel_obj.options['name'])))
  6489. elif curr_sel_obj.kind == 'geometry':
  6490. self.inform.emit(
  6491. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6492. color='red', name=str(curr_sel_obj.options['name'])))
  6493. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6494. self.collection.set_all_inactive()
  6495. self.delete_selection_shape()
  6496. self.collection.set_active(objects_under_the_click_list[0])
  6497. # create the selection box around the selected object
  6498. curr_sel_obj = self.collection.get_active()
  6499. if self.defaults['global_selection_shape'] is True:
  6500. self.draw_selection_shape(curr_sel_obj)
  6501. # self.inform.emit('[selected] %s: %s selected' %
  6502. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6503. if curr_sel_obj.kind == 'gerber':
  6504. self.inform.emit(
  6505. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6506. color='green', name=str(curr_sel_obj.options['name'])))
  6507. elif curr_sel_obj.kind == 'excellon':
  6508. self.inform.emit(
  6509. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6510. color='brown', name=str(curr_sel_obj.options['name'])))
  6511. elif curr_sel_obj.kind == 'cncjob':
  6512. self.inform.emit(
  6513. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6514. color='blue', name=str(curr_sel_obj.options['name'])))
  6515. elif curr_sel_obj.kind == 'geometry':
  6516. self.inform.emit(
  6517. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6518. color='red', name=str(curr_sel_obj.options['name'])))
  6519. else:
  6520. self.collection.set_all_inactive()
  6521. self.delete_selection_shape()
  6522. if self.call_source == 'app':
  6523. # delete any text in the status bar, implicitly the last object name that was selected
  6524. self.inform.emit("")
  6525. else:
  6526. self.call_source = 'app'
  6527. else:
  6528. # If there is no selected object
  6529. # make active the first element of the overlapped objects list
  6530. if self.collection.get_active() is None:
  6531. self.collection.set_active(objects_under_the_click_list[0])
  6532. name_sel_obj = self.collection.get_active().options['name']
  6533. # In case that there is a selected object but it is not in the overlapped object list
  6534. # make that object inactive and activate the first element in the overlapped object list
  6535. if name_sel_obj not in objects_under_the_click_list:
  6536. self.collection.set_inactive(name_sel_obj)
  6537. name_sel_obj = objects_under_the_click_list[0]
  6538. self.collection.set_active(name_sel_obj)
  6539. else:
  6540. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6541. self.collection.set_all_inactive()
  6542. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6543. len(objects_under_the_click_list)])
  6544. curr_sel_obj = self.collection.get_active()
  6545. # delete the possible selection box around a possible selected object
  6546. self.delete_selection_shape()
  6547. # create the selection box around the selected object
  6548. if self.defaults['global_selection_shape'] is True:
  6549. self.draw_selection_shape(curr_sel_obj)
  6550. # self.inform.emit('[selected] %s: %s selected' %
  6551. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6552. if curr_sel_obj.kind == 'gerber':
  6553. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6554. color='green', name=str(curr_sel_obj.options['name'])))
  6555. elif curr_sel_obj.kind == 'excellon':
  6556. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6557. color='brown', name=str(curr_sel_obj.options['name'])))
  6558. elif curr_sel_obj.kind == 'cncjob':
  6559. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6560. color='blue', name=str(curr_sel_obj.options['name'])))
  6561. elif curr_sel_obj.kind == 'geometry':
  6562. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6563. color='red', name=str(curr_sel_obj.options['name'])))
  6564. # for obj in self.collection.get_list():
  6565. # obj.plot()
  6566. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6567. # TODO: on selected objects change the object colors and do not draw the selection box
  6568. # self.plotcanvas.update() # this updates the canvas
  6569. except Exception as e:
  6570. log.error("[ERROR] Something went bad. %s" % str(e))
  6571. return
  6572. def delete_hover_shape(self):
  6573. self.hover_shapes.clear()
  6574. self.hover_shapes.redraw()
  6575. def draw_hover_shape(self, sel_obj, color=None):
  6576. """
  6577. :param sel_obj: the object for which the hover shape must be drawn
  6578. :return:
  6579. """
  6580. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6581. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6582. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6583. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6584. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6585. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6586. hover_rect = hover_rect.buffer(-0.1)
  6587. hover_rect = hover_rect.buffer(0.2)
  6588. else:
  6589. hover_rect = hover_rect.buffer(-0.00393)
  6590. hover_rect = hover_rect.buffer(0.00787)
  6591. if color:
  6592. face = Color(color)
  6593. face.alpha = 0.2
  6594. outline = Color(color, alpha=0.8)
  6595. else:
  6596. face = Color(self.defaults['global_sel_fill'])
  6597. face.alpha = 0.2
  6598. outline = self.defaults['global_sel_line']
  6599. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6600. def delete_selection_shape(self):
  6601. self.move_tool.sel_shapes.clear()
  6602. self.move_tool.sel_shapes.redraw()
  6603. def draw_selection_shape(self, sel_obj, color=None):
  6604. """
  6605. :param sel_obj: the object for which the selection shape must be drawn
  6606. :return:
  6607. """
  6608. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6609. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6610. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6611. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6612. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6613. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6614. sel_rect = sel_rect.buffer(-0.1)
  6615. sel_rect = sel_rect.buffer(0.2)
  6616. else:
  6617. sel_rect = sel_rect.buffer(-0.00393)
  6618. sel_rect = sel_rect.buffer(0.00787)
  6619. if color:
  6620. face = Color(color, alpha=0.2)
  6621. outline = Color(color, alpha=0.8)
  6622. else:
  6623. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6624. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6625. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6626. color=outline,
  6627. face_color=face,
  6628. update=True,
  6629. layer=0,
  6630. tolerance=None))
  6631. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6632. """
  6633. :param old_coords: old coordinates
  6634. :param coords: new coordinates
  6635. :return:
  6636. """
  6637. if 'color' in kwargs:
  6638. color = kwargs['color']
  6639. else:
  6640. color = self.defaults['global_sel_line']
  6641. if 'face_color' in kwargs:
  6642. face_color = kwargs['face_color']
  6643. else:
  6644. face_color = self.defaults['global_sel_fill']
  6645. if 'face_alpha' in kwargs:
  6646. face_alpha = kwargs['face_alpha']
  6647. else:
  6648. face_alpha = 0.3
  6649. x0, y0 = old_coords
  6650. x1, y1 = coords
  6651. pt1 = (x0, y0)
  6652. pt2 = (x1, y0)
  6653. pt3 = (x1, y1)
  6654. pt4 = (x0, y1)
  6655. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6656. color_t = Color(face_color)
  6657. color_t.alpha = face_alpha
  6658. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6659. layer=0, tolerance=None)
  6660. def on_file_new_click(self):
  6661. if self.collection.get_list() and self.should_we_save:
  6662. msgbox = QtWidgets.QMessageBox()
  6663. # msgbox.setText("<B>Save changes ...</B>")
  6664. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6665. "Creating a New project will delete them.\n"
  6666. "Do you want to Save the project?"))
  6667. msgbox.setWindowTitle(_("Save changes"))
  6668. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6669. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6670. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6671. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6672. msgbox.setDefaultButton(bt_yes)
  6673. msgbox.exec_()
  6674. response = msgbox.clickedButton()
  6675. if response == bt_yes:
  6676. self.on_file_saveprojectas()
  6677. elif response == bt_cancel:
  6678. return
  6679. elif response == bt_no:
  6680. self.on_file_new()
  6681. else:
  6682. self.on_file_new()
  6683. self.inform.emit('[success] %s...' %
  6684. _("New Project created"))
  6685. def on_file_new(self, cli=None):
  6686. """
  6687. Callback for menu item File->New. Returns the application to its
  6688. startup state. This method is thread-safe.
  6689. :return: None
  6690. """
  6691. self.report_usage("on_file_new")
  6692. # Remove everything from memory
  6693. App.log.debug("on_file_new()")
  6694. if self.call_source != 'app':
  6695. self.editor2object(cleanup=True)
  6696. # ## EDITOR section
  6697. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6698. self.exc_editor = FlatCAMExcEditor(self)
  6699. self.grb_editor = FlatCAMGrbEditor(self)
  6700. # Clear pool
  6701. self.clear_pool()
  6702. for obj in self.collection.get_list():
  6703. # delete shapes left drawn from mark shape_collections, if any
  6704. if isinstance(obj, FlatCAMGerber):
  6705. try:
  6706. obj.mark_shapes.enabled = False
  6707. obj.mark_shapes.clear(update=True)
  6708. except AttributeError:
  6709. pass
  6710. # also delete annotation shapes, if any
  6711. elif isinstance(obj, FlatCAMCNCjob):
  6712. try:
  6713. obj.annotation.enabled = False
  6714. obj.annotation.clear(update=True)
  6715. except AttributeError:
  6716. pass
  6717. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6718. self.init_tcl()
  6719. self.delete_selection_shape()
  6720. self.collection.delete_all()
  6721. self.setup_component_editor()
  6722. # Clear project filename
  6723. self.project_filename = None
  6724. # Load the application defaults
  6725. self.load_defaults(filename='current_defaults')
  6726. # Re-fresh project options
  6727. self.on_options_app2project()
  6728. # Init Tools
  6729. self.init_tools()
  6730. if cli is None:
  6731. # Close any Tabs opened in the Plot Tab Area section
  6732. for index in range(self.ui.plot_tab_area.count()):
  6733. self.ui.plot_tab_area.closeTab(index)
  6734. # for whatever reason previous command does not close the last tab so I do it manually
  6735. self.ui.plot_tab_area.closeTab(0)
  6736. # # And then add again the Plot Area
  6737. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6738. self.ui.plot_tab_area.protectTab(0)
  6739. # take the focus of the Notebook on Project Tab.
  6740. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6741. self.set_ui_title(name=_("New Project - Not saved"))
  6742. def obj_properties(self):
  6743. self.report_usage("obj_properties()")
  6744. self.properties_tool.run(toggle=False)
  6745. def on_project_context_save(self):
  6746. obj = self.collection.get_active()
  6747. if type(obj) == FlatCAMGeometry:
  6748. self.on_file_exportdxf()
  6749. elif type(obj) == FlatCAMExcellon:
  6750. self.on_file_saveexcellon()
  6751. elif type(obj) == FlatCAMCNCjob:
  6752. obj.on_exportgcode_button_click()
  6753. elif type(obj) == FlatCAMGerber:
  6754. self.on_file_savegerber()
  6755. def obj_move(self):
  6756. self.report_usage("obj_move()")
  6757. self.move_tool.run(toggle=False)
  6758. def on_fileopengerber(self, checked=None, name=None):
  6759. """
  6760. File menu callback for opening a Gerber.
  6761. :return: None
  6762. """
  6763. self.report_usage("on_fileopengerber")
  6764. App.log.debug("on_fileopengerber()")
  6765. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6766. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6767. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6768. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6769. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6770. "*.mil);;" \
  6771. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6772. "Allegro Files (*.art);;" \
  6773. "Mentor Files (*.pho *.gdo);;" \
  6774. "All Files (*.*)"
  6775. if name is None:
  6776. try:
  6777. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6778. directory=self.get_last_folder(),
  6779. filter=_filter_)
  6780. except TypeError:
  6781. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6782. filenames = [str(filename) for filename in filenames]
  6783. else:
  6784. filenames = [name]
  6785. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6786. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6787. _("Opening Gerber file.")),
  6788. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6789. color=QtGui.QColor("gray"))
  6790. if len(filenames) == 0:
  6791. self.inform.emit('[WARNING_NOTCL] %s' %
  6792. _("Open Gerber cancelled."))
  6793. else:
  6794. for filename in filenames:
  6795. if filename != '':
  6796. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6797. def on_fileopenexcellon(self, checked=None, name=None):
  6798. """
  6799. File menu callback for opening an Excellon file.
  6800. :return: None
  6801. """
  6802. self.report_usage("on_fileopenexcellon")
  6803. App.log.debug("on_fileopenexcellon()")
  6804. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6805. "All Files (*.*)"
  6806. if name is None:
  6807. try:
  6808. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6809. directory=self.get_last_folder(),
  6810. filter=_filter_)
  6811. except TypeError:
  6812. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6813. filenames = [str(filename) for filename in filenames]
  6814. else:
  6815. filenames = [str(name)]
  6816. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6817. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6818. _("Opening Excellon file.")),
  6819. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6820. color=QtGui.QColor("gray"))
  6821. if len(filenames) == 0:
  6822. self.inform.emit('[WARNING_NOTCL]%s' %
  6823. _(" Open Excellon cancelled."))
  6824. else:
  6825. for filename in filenames:
  6826. if filename != '':
  6827. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6828. def on_fileopengcode(self, checked=None, name=None):
  6829. """
  6830. File menu call back for opening gcode.
  6831. :return: None
  6832. """
  6833. self.report_usage("on_fileopengcode")
  6834. App.log.debug("on_fileopengcode()")
  6835. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6836. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6837. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6838. "All Files (*.*)"
  6839. if name is None:
  6840. try:
  6841. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6842. directory=self.get_last_folder(),
  6843. filter=_filter_)
  6844. except TypeError:
  6845. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6846. filenames = [str(filename) for filename in filenames]
  6847. else:
  6848. filenames = [name]
  6849. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6850. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6851. _("Opening G-Code file.")),
  6852. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6853. color=QtGui.QColor("gray"))
  6854. if len(filenames) == 0:
  6855. self.inform.emit('[WARNING_NOTCL] %s' %
  6856. _("Open G-Code cancelled."))
  6857. else:
  6858. for filename in filenames:
  6859. if filename != '':
  6860. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6861. def on_file_openproject(self, checked=None):
  6862. """
  6863. File menu callback for opening a project.
  6864. :return: None
  6865. """
  6866. self.report_usage("on_file_openproject")
  6867. App.log.debug("on_file_openproject()")
  6868. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6869. try:
  6870. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6871. directory=self.get_last_folder(), filter=_filter_)
  6872. except TypeError:
  6873. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6874. # The Qt methods above will return a QString which can cause problems later.
  6875. # So far json.dump() will fail to serialize it.
  6876. # TODO: Improve the serialization methods and remove this fix.
  6877. filename = str(filename)
  6878. if filename == "":
  6879. self.inform.emit('[WARNING_NOTCL] %s' %
  6880. _("Open Project cancelled."))
  6881. else:
  6882. # self.worker_task.emit({'fcn': self.open_project,
  6883. # 'params': [filename]})
  6884. # The above was failing because open_project() is not
  6885. # thread safe. The new_project()
  6886. self.open_project(filename)
  6887. def on_file_openconfig(self, checked=None):
  6888. """
  6889. File menu callback for opening a config file.
  6890. :return: None
  6891. """
  6892. self.report_usage("on_file_openconfig")
  6893. App.log.debug("on_file_openconfig()")
  6894. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6895. try:
  6896. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6897. directory=self.data_path, filter=_filter_)
  6898. except TypeError:
  6899. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6900. filter=_filter_)
  6901. if filename == "":
  6902. self.inform.emit('[WARNING_NOTCL] %s' %
  6903. _("Open Config cancelled."))
  6904. else:
  6905. self.open_config_file(filename)
  6906. def on_file_exportsvg(self):
  6907. """
  6908. Callback for menu item File->Export SVG.
  6909. :return: None
  6910. """
  6911. self.report_usage("on_file_exportsvg")
  6912. App.log.debug("on_file_exportsvg()")
  6913. obj = self.collection.get_active()
  6914. if obj is None:
  6915. self.inform.emit('[WARNING_NOTCL] %s' %
  6916. _("No object selected."))
  6917. msg = _("Please Select a Geometry object to export")
  6918. msgbox = QtWidgets.QMessageBox()
  6919. msgbox.setInformativeText(msg)
  6920. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6921. msgbox.setDefaultButton(bt_ok)
  6922. msgbox.exec_()
  6923. return
  6924. # Check for more compatible types and add as required
  6925. if (not isinstance(obj, FlatCAMGeometry)
  6926. and not isinstance(obj, FlatCAMGerber)
  6927. and not isinstance(obj, FlatCAMCNCjob)
  6928. and not isinstance(obj, FlatCAMExcellon)):
  6929. msg = '[ERROR_NOTCL] %s' % \
  6930. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6931. msgbox = QtWidgets.QMessageBox()
  6932. msgbox.setInformativeText(msg)
  6933. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6934. msgbox.setDefaultButton(bt_ok)
  6935. msgbox.exec_()
  6936. return
  6937. name = obj.options["name"]
  6938. _filter = "SVG File (*.svg);;All Files (*.*)"
  6939. try:
  6940. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6941. caption=_("Export SVG"),
  6942. directory=self.get_last_save_folder() + '/' + str(name),
  6943. filter=_filter)
  6944. except TypeError:
  6945. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6946. filename = str(filename)
  6947. if filename == "":
  6948. self.inform.emit('[WARNING_NOTCL]%s' %
  6949. _(" Export SVG cancelled."))
  6950. return
  6951. else:
  6952. self.export_svg(name, filename)
  6953. if self.defaults["global_open_style"] is False:
  6954. self.file_opened.emit("SVG", filename)
  6955. self.file_saved.emit("SVG", filename)
  6956. def on_file_exportpng(self):
  6957. self.report_usage("on_file_exportpng")
  6958. App.log.debug("on_file_exportpng()")
  6959. self.date = str(datetime.today()).rpartition('.')[0]
  6960. self.date = ''.join(c for c in self.date if c not in ':-')
  6961. self.date = self.date.replace(' ', '_')
  6962. image = _screenshot()
  6963. data = np.asarray(image)
  6964. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6965. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6966. _('Data must be a 3D array with last dimension 3 or 4'))
  6967. return
  6968. filter_ = "PNG File (*.png);;All Files (*.*)"
  6969. try:
  6970. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6971. caption=_("Export PNG Image"),
  6972. directory=self.get_last_save_folder() + '/png_' + self.date,
  6973. filter=filter_)
  6974. except TypeError:
  6975. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6976. filename = str(filename)
  6977. if filename == "":
  6978. self.inform.emit(_("Export PNG cancelled."))
  6979. return
  6980. else:
  6981. write_png(filename, data)
  6982. if self.defaults["global_open_style"] is False:
  6983. self.file_opened.emit("png", filename)
  6984. self.file_saved.emit("png", filename)
  6985. def on_file_savegerber(self):
  6986. """
  6987. Callback for menu item in Project context menu.
  6988. :return: None
  6989. """
  6990. self.report_usage("on_file_savegerber")
  6991. App.log.debug("on_file_savegerber()")
  6992. obj = self.collection.get_active()
  6993. if obj is None:
  6994. self.inform.emit('[WARNING_NOTCL] %s' %
  6995. _("No object selected. Please select an Gerber object to export."))
  6996. return
  6997. # Check for more compatible types and add as required
  6998. if not isinstance(obj, FlatCAMGerber):
  6999. self.inform.emit('[ERROR_NOTCL] %s' %
  7000. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7001. return
  7002. name = self.collection.get_active().options["name"]
  7003. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7004. try:
  7005. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7006. caption="Save Gerber source file",
  7007. directory=self.get_last_save_folder() + '/' + name,
  7008. filter=_filter)
  7009. except TypeError:
  7010. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7011. filename = str(filename)
  7012. if filename == "":
  7013. self.inform.emit('[WARNING_NOTCL] %s' %
  7014. _("Save Gerber source file cancelled."))
  7015. return
  7016. else:
  7017. self.save_source_file(name, filename)
  7018. if self.defaults["global_open_style"] is False:
  7019. self.file_opened.emit("Gerber", filename)
  7020. self.file_saved.emit("Gerber", filename)
  7021. def on_file_saveexcellon(self):
  7022. """
  7023. Callback for menu item in project context menu.
  7024. :return: None
  7025. """
  7026. self.report_usage("on_file_saveexcellon")
  7027. App.log.debug("on_file_saveexcellon()")
  7028. obj = self.collection.get_active()
  7029. if obj is None:
  7030. self.inform.emit('[WARNING_NOTCL] %s' %
  7031. _("No object selected. Please select an Excellon object to export."))
  7032. return
  7033. # Check for more compatible types and add as required
  7034. if not isinstance(obj, FlatCAMExcellon):
  7035. self.inform.emit('[ERROR_NOTCL] %s' %
  7036. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7037. return
  7038. name = self.collection.get_active().options["name"]
  7039. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7040. try:
  7041. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7042. caption=_("Save Excellon source file"),
  7043. directory=self.get_last_save_folder() + '/' + name,
  7044. filter=_filter)
  7045. except TypeError:
  7046. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7047. filename = str(filename)
  7048. if filename == "":
  7049. self.inform.emit('[WARNING_NOTCL] %s' %
  7050. _("Saving Excellon source file cancelled."))
  7051. return
  7052. else:
  7053. self.save_source_file(name, filename)
  7054. if self.defaults["global_open_style"] is False:
  7055. self.file_opened.emit("Excellon", filename)
  7056. self.file_saved.emit("Excellon", filename)
  7057. def on_file_exportexcellon(self):
  7058. """
  7059. Callback for menu item File->Export->Excellon.
  7060. :return: None
  7061. """
  7062. self.report_usage("on_file_exportexcellon")
  7063. App.log.debug("on_file_exportexcellon()")
  7064. obj = self.collection.get_active()
  7065. if obj is None:
  7066. self.inform.emit('[WARNING_NOTCL] %s' %
  7067. _("No object selected. Please Select an Excellon object to export."))
  7068. return
  7069. # Check for more compatible types and add as required
  7070. if not isinstance(obj, FlatCAMExcellon):
  7071. self.inform.emit('[ERROR_NOTCL] %s' %
  7072. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7073. return
  7074. name = self.collection.get_active().options["name"]
  7075. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7076. try:
  7077. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7078. caption=_("Export Excellon"),
  7079. directory=self.get_last_save_folder() + '/' + name,
  7080. filter=_filter)
  7081. except TypeError:
  7082. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7083. filename = str(filename)
  7084. if filename == "":
  7085. self.inform.emit('[WARNING_NOTCL] %s' %
  7086. _("Export Excellon cancelled."))
  7087. return
  7088. else:
  7089. self.export_excellon(name, filename)
  7090. if self.defaults["global_open_style"] is False:
  7091. self.file_opened.emit("Excellon", filename)
  7092. self.file_saved.emit("Excellon", filename)
  7093. def on_file_exportgerber(self):
  7094. """
  7095. Callback for menu item File->Export->Gerber.
  7096. :return: None
  7097. """
  7098. self.report_usage("on_file_exportgerber")
  7099. App.log.debug("on_file_exportgerber()")
  7100. obj = self.collection.get_active()
  7101. if obj is None:
  7102. self.inform.emit('[WARNING_NOTCL] %s' %
  7103. _("No object selected. Please Select an Gerber object to export."))
  7104. return
  7105. # Check for more compatible types and add as required
  7106. if not isinstance(obj, FlatCAMGerber):
  7107. self.inform.emit('[ERROR_NOTCL] %s' %
  7108. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7109. return
  7110. name = self.collection.get_active().options["name"]
  7111. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7112. try:
  7113. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7114. caption=_("Export Gerber"),
  7115. directory=self.get_last_save_folder() + '/' + name,
  7116. filter=_filter_)
  7117. except TypeError:
  7118. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7119. filename = str(filename)
  7120. if filename == "":
  7121. self.inform.emit('[WARNING_NOTCL] %s' %
  7122. _("Export Gerber cancelled."))
  7123. return
  7124. else:
  7125. self.export_gerber(name, filename)
  7126. if self.defaults["global_open_style"] is False:
  7127. self.file_opened.emit("Gerber", filename)
  7128. self.file_saved.emit("Gerber", filename)
  7129. def on_file_exportdxf(self):
  7130. """
  7131. Callback for menu item File->Export DXF.
  7132. :return: None
  7133. """
  7134. self.report_usage("on_file_exportdxf")
  7135. App.log.debug("on_file_exportdxf()")
  7136. obj = self.collection.get_active()
  7137. if obj is None:
  7138. self.inform.emit('[WARNING_NOTCL] %s' %
  7139. _("No object selected."))
  7140. msg = _("Please Select a Geometry object to export")
  7141. msgbox = QtWidgets.QMessageBox()
  7142. msgbox.setInformativeText(msg)
  7143. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7144. msgbox.setDefaultButton(bt_ok)
  7145. msgbox.exec_()
  7146. return
  7147. # Check for more compatible types and add as required
  7148. if not isinstance(obj, FlatCAMGeometry):
  7149. msg = '[ERROR_NOTCL] %s' % \
  7150. _("Only Geometry objects can be used.")
  7151. msgbox = QtWidgets.QMessageBox()
  7152. msgbox.setInformativeText(msg)
  7153. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7154. msgbox.setDefaultButton(bt_ok)
  7155. msgbox.exec_()
  7156. return
  7157. name = self.collection.get_active().options["name"]
  7158. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7159. try:
  7160. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7161. caption=_("Export DXF"),
  7162. directory=self.get_last_save_folder() + '/' + name,
  7163. filter=_filter_)
  7164. except TypeError:
  7165. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7166. filter=_filter_)
  7167. filename = str(filename)
  7168. if filename == "":
  7169. self.inform.emit('[WARNING_NOTCL] %s' %
  7170. _("Export DXF cancelled."))
  7171. return
  7172. else:
  7173. self.export_dxf(name, filename)
  7174. if self.defaults["global_open_style"] is False:
  7175. self.file_opened.emit("DXF", filename)
  7176. self.file_saved.emit("DXF", filename)
  7177. def on_file_importsvg(self, type_of_obj):
  7178. """
  7179. Callback for menu item File->Import SVG.
  7180. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7181. :type type_of_obj: str
  7182. :return: None
  7183. """
  7184. self.report_usage("on_file_importsvg")
  7185. App.log.debug("on_file_importsvg()")
  7186. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7187. try:
  7188. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7189. directory=self.get_last_folder(), filter=_filter_)
  7190. except TypeError:
  7191. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7192. filter=_filter_)
  7193. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7194. type_of_obj = "geometry"
  7195. filenames = [str(filename) for filename in filenames]
  7196. if len(filenames) == 0:
  7197. self.inform.emit('[WARNING_NOTCL] %s' %
  7198. _("Open SVG cancelled."))
  7199. else:
  7200. for filename in filenames:
  7201. if filename != '':
  7202. self.worker_task.emit({'fcn': self.import_svg,
  7203. 'params': [filename, type_of_obj]})
  7204. def on_file_importdxf(self, type_of_obj):
  7205. """
  7206. Callback for menu item File->Import DXF.
  7207. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7208. :type type_of_obj: str
  7209. :return: None
  7210. """
  7211. self.report_usage("on_file_importdxf")
  7212. App.log.debug("on_file_importdxf()")
  7213. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7214. try:
  7215. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7216. directory=self.get_last_folder(),
  7217. filter=_filter_)
  7218. except TypeError:
  7219. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7220. filter=_filter_)
  7221. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7222. type_of_obj = "geometry"
  7223. filenames = [str(filename) for filename in filenames]
  7224. if len(filenames) == 0:
  7225. self.inform.emit('[WARNING_NOTCL] %s' %
  7226. _("Open DXF cancelled."))
  7227. else:
  7228. for filename in filenames:
  7229. if filename != '':
  7230. self.worker_task.emit({'fcn': self.import_dxf,
  7231. 'params': [filename, type_of_obj]})
  7232. # ###############################################################################################################
  7233. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7234. # ###############################################################################################################
  7235. def init_code_editor(self, name):
  7236. # Signals section
  7237. # Disconnect the old signals
  7238. try:
  7239. self.ui.buttonOpen.clicked.disconnect()
  7240. except TypeError:
  7241. pass
  7242. try:
  7243. self.ui.buttonSave.clicked.disconnect()
  7244. except TypeError:
  7245. pass
  7246. # add the tab if it was closed
  7247. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7248. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7249. # delete the absolute and relative position and messages in the infobar
  7250. self.ui.position_label.setText("")
  7251. self.ui.rel_position_label.setText("")
  7252. # first clear previous text in text editor (if any)
  7253. self.ui.code_editor.clear()
  7254. self.ui.code_editor.setReadOnly(False)
  7255. self.toggle_codeeditor = True
  7256. self.ui.code_editor.completer_enable = False
  7257. self.ui.buttonRun.hide()
  7258. # make sure to keep a reference to the code editor
  7259. self.reference_code_editor = self.ui.code_editor
  7260. # Switch plot_area to CNCJob tab
  7261. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7262. def on_view_source(self):
  7263. self.inform.emit('%s' %
  7264. _("Viewing the source code of the selected object."))
  7265. self.proc_container.view.set_busy(_("Loading..."))
  7266. try:
  7267. obj = self.collection.get_active()
  7268. except Exception as e:
  7269. log.debug("App.on_view_source() --> %s" % str(e))
  7270. self.inform.emit('[WARNING_NOTCL] %s' %
  7271. _("Select an Gerber or Excellon file to view it's source file."))
  7272. return 'fail'
  7273. if obj.kind == 'gerber':
  7274. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7275. elif obj.kind == 'excellon':
  7276. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7277. elif obj.kind == 'cncjob':
  7278. "GCode Files (*.NC);;All Files (*.*)"
  7279. else:
  7280. flt = "All Files (*.*)"
  7281. self.init_code_editor(name=_("Source Editor"))
  7282. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7283. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7284. # then append the text from GCode to the text editor
  7285. if obj.kind == 'cncjob':
  7286. try:
  7287. file = obj.export_gcode(
  7288. preamble=self.defaults["cncjob_prepend"],
  7289. postamble=self.defaults["cncjob_append"],
  7290. to_file=True)
  7291. if file == 'fail':
  7292. return 'fail'
  7293. except AttributeError:
  7294. self.inform.emit('[WARNING_NOTCL] %s' %
  7295. _("There is no selected object for which to see it's source file code."))
  7296. return 'fail'
  7297. else:
  7298. try:
  7299. file = StringIO(obj.source_file)
  7300. except AttributeError:
  7301. self.inform.emit('[WARNING_NOTCL] %s' %
  7302. _("There is no selected object for which to see it's source file code."))
  7303. return 'fail'
  7304. self.ui.cncjob_frame.hide()
  7305. try:
  7306. for line in file:
  7307. QtWidgets.QApplication.processEvents()
  7308. proc_line = str(line).strip('\n')
  7309. self.ui.code_editor.append(proc_line)
  7310. except Exception as e:
  7311. log.debug('App.on_view_source() -->%s' % str(e))
  7312. self.inform.emit('[ERROR] %s: %s' %
  7313. (_('Failed to load the source code for the selected object'), str(e)))
  7314. return
  7315. self.handleTextChanged()
  7316. self.ui.cncjob_frame.show()
  7317. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7318. self.proc_container.view.set_idle()
  7319. # self.ui.show()
  7320. def on_toggle_code_editor(self):
  7321. self.report_usage("on_toggle_code_editor()")
  7322. if self.toggle_codeeditor is False:
  7323. self.init_code_editor(name=_("Code Editor"))
  7324. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7325. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7326. else:
  7327. for idx in range(self.ui.plot_tab_area.count()):
  7328. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7329. self.ui.plot_tab_area.closeTab(idx)
  7330. break
  7331. self.toggle_codeeditor = False
  7332. def on_filenewscript(self):
  7333. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7334. self.init_code_editor(name=_("Script Editor"))
  7335. self.ui.code_editor.completer_enable = True
  7336. self.ui.code_editor.append(_(
  7337. "#\n"
  7338. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7339. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7340. "#\n\n"
  7341. "# FlatCAM commands list:\n"
  7342. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7343. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7344. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7345. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7346. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7347. "# SubtractRectangle, Version, WriteGCode\n"
  7348. "#\n\n"
  7349. ))
  7350. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7351. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7352. self.ui.buttonRun.show()
  7353. try:
  7354. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7355. except TypeError:
  7356. pass
  7357. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7358. self.handleTextChanged()
  7359. self.ui.code_editor.show()
  7360. def on_fileopenscript(self):
  7361. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7362. try:
  7363. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7364. directory=self.get_last_folder(), filter=_filter_)
  7365. except TypeError:
  7366. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7367. # The Qt methods above will return a QString which can cause problems later.
  7368. # So far json.dump() will fail to serialize it.
  7369. # TODO: Improve the serialization methods and remove this fix.
  7370. filename = str(filename)
  7371. if filename == "":
  7372. self.inform.emit('[WARNING_NOTCL] %s' %
  7373. _("Open TCL script cancelled."))
  7374. else:
  7375. self.on_filenewscript()
  7376. try:
  7377. with open(filename, "r") as opened_script:
  7378. try:
  7379. for line in opened_script:
  7380. proc_line = str(line).strip('\n')
  7381. self.ui.code_editor.append(proc_line)
  7382. except Exception as e:
  7383. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7384. self.inform.emit('[ERROR] %s %s' %
  7385. (_('App.on_fileopenscript() -->'), str(e)))
  7386. return
  7387. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7388. self.handleTextChanged()
  7389. # self.ui.show()
  7390. except Exception as e:
  7391. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7392. def on_filerunscript(self, name=None):
  7393. """
  7394. File menu callback for loading and running a TCL script.
  7395. :return: None
  7396. """
  7397. self.report_usage("on_filerunscript")
  7398. App.log.debug("on_file_runscript()")
  7399. if name:
  7400. filename = name
  7401. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7402. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7403. _("Executing FlatCAMScript file.")),
  7404. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7405. color=QtGui.QColor("gray"))
  7406. else:
  7407. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7408. try:
  7409. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7410. directory=self.get_last_folder(), filter=_filter_)
  7411. except TypeError:
  7412. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7413. # The Qt methods above will return a QString which can cause problems later.
  7414. # So far json.dump() will fail to serialize it.
  7415. # TODO: Improve the serialization methods and remove this fix.
  7416. filename = str(filename)
  7417. if filename == "":
  7418. self.inform.emit('[WARNING_NOTCL] %s' %
  7419. _("Run TCL script cancelled."))
  7420. else:
  7421. try:
  7422. with open(filename, "r") as tcl_script:
  7423. cmd_line_shellfile_content = tcl_script.read()
  7424. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7425. except Exception as e:
  7426. log.debug("App.on_filerunscript() -> %s" % str(e))
  7427. sys.exit(2)
  7428. def on_file_saveproject(self):
  7429. """
  7430. Callback for menu item File->Save Project. Saves the project to
  7431. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7432. if set to None. The project is saved by calling ``self.save_project()``.
  7433. :return: None
  7434. """
  7435. self.report_usage("on_file_saveproject")
  7436. if self.project_filename is None:
  7437. self.on_file_saveprojectas()
  7438. else:
  7439. self.worker_task.emit({'fcn': self.save_project,
  7440. 'params': [self.project_filename]})
  7441. if self.defaults["global_open_style"] is False:
  7442. self.file_opened.emit("project", self.project_filename)
  7443. self.file_saved.emit("project", self.project_filename)
  7444. self.set_ui_title(name=self.project_filename)
  7445. self.should_we_save = False
  7446. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7447. """
  7448. Callback for menu item File->Save Project As... Opens a file
  7449. chooser and saves the project to the given file via
  7450. ``self.save_project()``.
  7451. :param make_copy if to be create a copy of the project; boolean
  7452. :param use_thread: if to be run in a separate thread; boolean
  7453. :param quit_action: if to be followed by quiting the application; boolean
  7454. :return: None
  7455. """
  7456. self.report_usage("on_file_saveprojectas")
  7457. self.date = str(datetime.today()).rpartition('.')[0]
  7458. self.date = ''.join(c for c in self.date if c not in ':-')
  7459. self.date = self.date.replace(' ', '_')
  7460. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7461. try:
  7462. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7463. caption=_("Save Project As ..."),
  7464. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7465. filter=filter_)
  7466. except TypeError:
  7467. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7468. filename = str(filename)
  7469. if filename == '':
  7470. self.inform.emit('[WARNING_NOTCL] %s' %
  7471. _("Save Project cancelled."))
  7472. return
  7473. try:
  7474. f = open(filename, 'r')
  7475. f.close()
  7476. except IOError:
  7477. pass
  7478. if use_thread is True:
  7479. self.worker_task.emit({'fcn': self.save_project,
  7480. 'params': [filename, quit_action]})
  7481. else:
  7482. self.save_project(filename, quit_action)
  7483. # self.save_project(filename)
  7484. if self.defaults["global_open_style"] is False:
  7485. self.file_opened.emit("project", filename)
  7486. self.file_saved.emit("project", filename)
  7487. if not make_copy:
  7488. self.project_filename = filename
  7489. self.set_ui_title(name=self.project_filename)
  7490. self.should_we_save = False
  7491. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7492. """
  7493. Exports a Geometry Object to an SVG file.
  7494. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7495. :param filename: Path to the SVG file to save to.
  7496. :param scale_factor: factor by which to change/scale the thickness of the features
  7497. :return:
  7498. """
  7499. self.report_usage("export_svg()")
  7500. if filename is None:
  7501. filename = self.defaults["global_last_save_folder"]
  7502. self.log.debug("export_svg()")
  7503. try:
  7504. obj = self.collection.get_by_name(str(obj_name))
  7505. except:
  7506. # TODO: The return behavior has not been established... should raise exception?
  7507. return "Could not retrieve object: %s" % obj_name
  7508. with self.proc_container.new(_("Exporting SVG")) as proc:
  7509. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7510. # Determine bounding area for svg export
  7511. bounds = obj.bounds()
  7512. size = obj.size()
  7513. # Convert everything to strings for use in the xml doc
  7514. svgwidth = str(size[0])
  7515. svgheight = str(size[1])
  7516. minx = str(bounds[0])
  7517. miny = str(bounds[1] - size[1])
  7518. uom = obj.units.lower()
  7519. # Add a SVG Header and footer to the svg output from shapely
  7520. # The transform flips the Y Axis so that everything renders
  7521. # properly within svg apps such as inkscape
  7522. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7523. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7524. svg_header += 'width="' + svgwidth + uom + '" '
  7525. svg_header += 'height="' + svgheight + uom + '" '
  7526. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7527. svg_header += '<g transform="scale(1,-1)">'
  7528. svg_footer = '</g> </svg>'
  7529. svg_elem = svg_header + exported_svg + svg_footer
  7530. # Parse the xml through a xml parser just to add line feeds
  7531. # and to make it look more pretty for the output
  7532. svgcode = parse_xml_string(svg_elem)
  7533. try:
  7534. with open(filename, 'w') as fp:
  7535. fp.write(svgcode.toprettyxml())
  7536. except PermissionError:
  7537. self.inform.emit('[WARNING] %s' %
  7538. _("Permission denied, saving not possible.\n"
  7539. "Most likely another app is holding the file open and not accessible."))
  7540. return 'fail'
  7541. if self.defaults["global_open_style"] is False:
  7542. self.file_opened.emit("SVG", filename)
  7543. self.file_saved.emit("SVG", filename)
  7544. self.inform.emit('[success] %s: %s' %
  7545. (_("SVG file exported to"), filename))
  7546. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7547. """
  7548. Exports a Geometry Object to an SVG file in negative.
  7549. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7550. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7551. :param filename: Path to the SVG file to save to.
  7552. :param boundary: thickness of a black border to surround all the features
  7553. :param scale_factor: factor by which to change/scale the thickness of the features
  7554. :param use_thread: if to be run in a separate thread; boolean
  7555. :return:
  7556. """
  7557. self.report_usage("export_negative()")
  7558. if filename is None:
  7559. filename = self.defaults["global_last_save_folder"]
  7560. self.log.debug("export_svg() negative")
  7561. try:
  7562. obj = self.collection.get_by_name(str(obj_name))
  7563. except:
  7564. # TODO: The return behavior has not been established... should raise exception?
  7565. return "Could not retrieve object: %s" % obj_name
  7566. try:
  7567. box = self.collection.get_by_name(str(box_name))
  7568. except:
  7569. # TODO: The return behavior has not been established... should raise exception?
  7570. return "Could not retrieve object: %s" % box_name
  7571. if box is None:
  7572. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7573. (_("No object Box. Using instead"), obj))
  7574. box = obj
  7575. def make_negative_film():
  7576. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7577. # Determine bounding area for svg export
  7578. bounds = box.bounds()
  7579. size = box.size()
  7580. uom = obj.units.lower()
  7581. # Convert everything to strings for use in the xml doc
  7582. svgwidth = str(size[0] + (2 * boundary))
  7583. svgheight = str(size[1] + (2 * boundary))
  7584. minx = str(bounds[0] - boundary)
  7585. miny = str(bounds[1] + boundary + size[1])
  7586. miny_rect = str(bounds[1] - boundary)
  7587. # Add a SVG Header and footer to the svg output from shapely
  7588. # The transform flips the Y Axis so that everything renders
  7589. # properly within svg apps such as inkscape
  7590. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7591. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7592. svg_header += 'width="' + svgwidth + uom + '" '
  7593. svg_header += 'height="' + svgheight + uom + '" '
  7594. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7595. svg_header += '>'
  7596. svg_header += '<g transform="scale(1,-1)">'
  7597. svg_footer = '</g> </svg>'
  7598. # Change the attributes of the exported SVG
  7599. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7600. # We set opacity to maximum
  7601. # We set the color to WHITE
  7602. root = ET.fromstring(exported_svg)
  7603. for child in root:
  7604. child.set('fill', '#FFFFFF')
  7605. child.set('opacity', '1.0')
  7606. child.set('stroke', '#FFFFFF')
  7607. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7608. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7609. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7610. first_svg_elem_tag = 'rect'
  7611. first_svg_elem_attribs = {
  7612. 'x': minx,
  7613. 'y': miny_rect,
  7614. 'width': svgwidth,
  7615. 'height': svgheight,
  7616. 'id': 'neg_rect',
  7617. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7618. }
  7619. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7620. exported_svg = ET.tostring(root)
  7621. svg_elem = svg_header + str(exported_svg) + svg_footer
  7622. # Parse the xml through a xml parser just to add line feeds
  7623. # and to make it look more pretty for the output
  7624. doc = parse_xml_string(svg_elem)
  7625. try:
  7626. with open(filename, 'w') as fp:
  7627. fp.write(doc.toprettyxml())
  7628. except PermissionError:
  7629. self.inform.emit('[WARNING] %s' %
  7630. _("Permission denied, saving not possible.\n"
  7631. "Most likely another app is holding the file open and not accessible."))
  7632. return 'fail'
  7633. if self.defaults["global_open_style"] is False:
  7634. self.file_opened.emit("SVG", filename)
  7635. self.file_saved.emit("SVG", filename)
  7636. self.inform.emit('[success] %s: %s' %
  7637. (_("SVG file exported to"), filename))
  7638. if use_thread is True:
  7639. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7640. def job_thread_film(app_obj):
  7641. try:
  7642. make_negative_film()
  7643. except Exception as e:
  7644. proc.done()
  7645. return
  7646. proc.done()
  7647. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7648. else:
  7649. make_negative_film()
  7650. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7651. """
  7652. Exports a Geometry Object to an SVG file in positive black.
  7653. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7654. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7655. :param filename: Path to the SVG file to save to.
  7656. :param scale_factor: factor by which to change/scale the thickness of the features
  7657. :param use_thread: if to be run in a separate thread; boolean
  7658. :return:
  7659. """
  7660. self.report_usage("export_svg_positive()")
  7661. if filename is None:
  7662. filename = self.defaults["global_last_save_folder"]
  7663. self.log.debug("export_svg() black")
  7664. try:
  7665. obj = self.collection.get_by_name(str(obj_name))
  7666. except:
  7667. # TODO: The return behavior has not been established... should raise exception?
  7668. return "Could not retrieve object: %s" % obj_name
  7669. try:
  7670. box = self.collection.get_by_name(str(box_name))
  7671. except:
  7672. # TODO: The return behavior has not been established... should raise exception?
  7673. return "Could not retrieve object: %s" % box_name
  7674. if box is None:
  7675. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7676. (_("No object Box. Using instead"), obj))
  7677. box = obj
  7678. def make_positive_film():
  7679. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7680. self.progress.emit(40)
  7681. # Change the attributes of the exported SVG
  7682. # We don't need stroke-width
  7683. # We set opacity to maximum
  7684. # We set the colour to WHITE
  7685. root = ET.fromstring(exported_svg)
  7686. for child in root:
  7687. child.set('fill', str(self.defaults['tools_film_color']))
  7688. child.set('opacity', '1.0')
  7689. child.set('stroke', str(self.defaults['tools_film_color']))
  7690. exported_svg = ET.tostring(root)
  7691. # Determine bounding area for svg export
  7692. bounds = box.bounds()
  7693. size = box.size()
  7694. # This contain the measure units
  7695. uom = obj.units.lower()
  7696. # Define a boundary around SVG of about 1.0mm (~39mils)
  7697. if uom in "mm":
  7698. boundary = 1.0
  7699. else:
  7700. boundary = 0.0393701
  7701. self.progress.emit(80)
  7702. # Convert everything to strings for use in the xml doc
  7703. svgwidth = str(size[0] + (2 * boundary))
  7704. svgheight = str(size[1] + (2 * boundary))
  7705. minx = str(bounds[0] - boundary)
  7706. miny = str(bounds[1] + boundary + size[1])
  7707. self.log.debug(minx)
  7708. self.log.debug(miny)
  7709. # Add a SVG Header and footer to the svg output from shapely
  7710. # The transform flips the Y Axis so that everything renders
  7711. # properly within svg apps such as inkscape
  7712. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7713. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7714. svg_header += 'width="' + svgwidth + uom + '" '
  7715. svg_header += 'height="' + svgheight + uom + '" '
  7716. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7717. svg_header += '>'
  7718. svg_header += '<g transform="scale(1,-1)">'
  7719. svg_footer = '</g> </svg>'
  7720. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7721. self.progress.emit(90)
  7722. # Parse the xml through a xml parser just to add line feeds
  7723. # and to make it look more pretty for the output
  7724. doc = parse_xml_string(svg_elem)
  7725. try:
  7726. with open(filename, 'w') as fp:
  7727. fp.write(doc.toprettyxml())
  7728. except PermissionError:
  7729. self.inform.emit('[WARNING] %s' %
  7730. _("Permission denied, saving not possible.\n"
  7731. "Most likely another app is holding the file open and not accessible."))
  7732. return 'fail'
  7733. self.progress.emit(100)
  7734. if self.defaults["global_open_style"] is False:
  7735. self.file_opened.emit("SVG", filename)
  7736. self.file_saved.emit("SVG", filename)
  7737. self.inform.emit('[success] %s: %s' %
  7738. (_("SVG file exported to"), filename))
  7739. if use_thread is True:
  7740. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7741. def job_thread_film(app_obj):
  7742. try:
  7743. make_positive_film()
  7744. except Exception as e:
  7745. proc.done()
  7746. return
  7747. proc.done()
  7748. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7749. else:
  7750. make_positive_film()
  7751. def save_source_file(self, obj_name, filename, use_thread=True):
  7752. """
  7753. Exports a FlatCAM Object to an Gerber/Excellon file.
  7754. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7755. :param filename: Path to the Gerber file to save to.
  7756. :param use_thread: if to be run in a separate thread
  7757. :return:
  7758. """
  7759. self.report_usage("save source file()")
  7760. if filename is None:
  7761. filename = self.defaults["global_last_save_folder"]
  7762. self.log.debug("save source file()")
  7763. obj = self.collection.get_by_name(obj_name)
  7764. file_string = StringIO(obj.source_file)
  7765. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7766. try:
  7767. with open(filename, 'w') as file:
  7768. file.writelines('G04*\n')
  7769. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7770. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7771. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7772. file.writelines('G04 Created on : %s*\n' % time_string)
  7773. for line in file_string:
  7774. file.writelines(line)
  7775. except PermissionError:
  7776. self.inform.emit('[WARNING] %s' %
  7777. _("Permission denied, saving not possible.\n"
  7778. "Most likely another app is holding the file open and not accessible."))
  7779. return 'fail'
  7780. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7781. """
  7782. Exports a Excellon Object to an Excellon file.
  7783. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7784. :param filename: Path to the Excellon file to save to.
  7785. :param use_thread: if to be run in a separate thread
  7786. :return:
  7787. """
  7788. self.report_usage("export_excellon()")
  7789. if filename is None:
  7790. filename = self.defaults["global_last_save_folder"]
  7791. self.log.debug("export_excellon()")
  7792. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7793. self.defaults["excellon_exp_decimals"]
  7794. )
  7795. units = ''
  7796. if local_use is None:
  7797. try:
  7798. obj = self.collection.get_by_name(str(obj_name))
  7799. except:
  7800. # TODO: The return behavior has not been established... should raise exception?
  7801. return "Could not retrieve object: %s" % obj_name
  7802. else:
  7803. obj = local_use
  7804. # updated units
  7805. eunits = self.defaults["excellon_exp_units"]
  7806. ewhole = self.defaults["excellon_exp_integer"]
  7807. efract = self.defaults["excellon_exp_decimals"]
  7808. ezeros = self.defaults["excellon_exp_zeros"]
  7809. eformat = self.defaults["excellon_exp_format"]
  7810. slot_type = self.defaults["excellon_exp_slot_type"]
  7811. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7812. if fc_units == 'MM':
  7813. factor = 1 if eunits == 'METRIC' else 0.03937
  7814. else:
  7815. factor = 25.4 if eunits == 'METRIC' else 1
  7816. def make_excellon():
  7817. try:
  7818. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7819. header = 'M48\n'
  7820. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7821. (str(self.version), str(self.version_date))
  7822. header += ';Filename: %s' % str(obj_name) + '\n'
  7823. header += ';Created on : %s' % time_str + '\n'
  7824. if eformat == 'dec':
  7825. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7826. header += eunits + '\n'
  7827. for tool in obj.tools:
  7828. if eunits == 'METRIC':
  7829. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7830. tool=str(tool),
  7831. dec=2)
  7832. else:
  7833. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7834. tool=str(tool),
  7835. dec=4)
  7836. else:
  7837. if ezeros == 'LZ':
  7838. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7839. form='ndec', e_zeros='LZ', factor=factor,
  7840. slot_type=slot_type)
  7841. header += '%s,%s\n' % (eunits, 'LZ')
  7842. header += format_exc
  7843. for tool in obj.tools:
  7844. if eunits == 'METRIC':
  7845. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7846. tool=str(tool),
  7847. dec=2)
  7848. else:
  7849. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7850. tool=str(tool),
  7851. dec=4)
  7852. else:
  7853. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7854. form='ndec', e_zeros='TZ', factor=factor,
  7855. slot_type=slot_type)
  7856. header += '%s,%s\n' % (eunits, 'TZ')
  7857. header += format_exc
  7858. for tool in obj.tools:
  7859. if eunits == 'METRIC':
  7860. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7861. tool=str(tool),
  7862. dec=2)
  7863. else:
  7864. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7865. tool=str(tool),
  7866. dec=4)
  7867. header += '%\n'
  7868. footer = 'M30\n'
  7869. exported_excellon = header
  7870. exported_excellon += excellon_code
  7871. exported_excellon += footer
  7872. if local_use is None:
  7873. try:
  7874. with open(filename, 'w') as fp:
  7875. fp.write(exported_excellon)
  7876. except PermissionError:
  7877. self.inform.emit('[WARNING] %s' %
  7878. _("Permission denied, saving not possible.\n"
  7879. "Most likely another app is holding the file open and not accessible."))
  7880. return 'fail'
  7881. if self.defaults["global_open_style"] is False:
  7882. self.file_opened.emit("Excellon", filename)
  7883. self.file_saved.emit("Excellon", filename)
  7884. self.inform.emit('[success] %s: %s' %
  7885. (_("Excellon file exported to"), filename))
  7886. else:
  7887. return exported_excellon
  7888. except Exception as e:
  7889. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7890. return 'fail'
  7891. if use_thread is True:
  7892. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7893. def job_thread_exc(app_obj):
  7894. ret = make_excellon()
  7895. if ret == 'fail':
  7896. self.inform.emit('[ERROR_NOTCL] %s' %
  7897. _('Could not export Excellon file.'))
  7898. return
  7899. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7900. else:
  7901. ret = make_excellon()
  7902. if ret == 'fail':
  7903. self.inform.emit('[ERROR_NOTCL] %s' %
  7904. _('Could not export Excellon file.'))
  7905. return 'fail'
  7906. if local_use is not None:
  7907. return ret
  7908. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7909. """
  7910. Exports a Gerber Object to an Gerber file.
  7911. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7912. :param filename: Path to the Gerber file to save to.
  7913. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7914. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7915. :param use_thread: if to be run in a separate thread
  7916. :return:
  7917. """
  7918. self.report_usage("export_gerber()")
  7919. if filename is None:
  7920. filename = self.defaults["global_last_save_folder"]
  7921. self.log.debug("export_gerber()")
  7922. if local_use is None:
  7923. try:
  7924. obj = self.collection.get_by_name(str(obj_name))
  7925. except:
  7926. # TODO: The return behavior has not been established... should raise exception?
  7927. return "Could not retrieve object: %s" % obj_name
  7928. else:
  7929. obj = local_use
  7930. # updated units
  7931. gunits = self.defaults["gerber_exp_units"]
  7932. gwhole = self.defaults["gerber_exp_integer"]
  7933. gfract = self.defaults["gerber_exp_decimals"]
  7934. gzeros = self.defaults["gerber_exp_zeros"]
  7935. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7936. if fc_units == 'MM':
  7937. factor = 1 if gunits == 'MM' else 0.03937
  7938. else:
  7939. factor = 25.4 if gunits == 'MM' else 1
  7940. def make_gerber():
  7941. try:
  7942. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7943. header = 'G04*\n'
  7944. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7945. (str(self.version), str(self.version_date))
  7946. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7947. header += 'G04 Created on : %s*' % time_str + '\n'
  7948. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7949. header += "%MO{units}*%\n".format(units=gunits)
  7950. for apid in obj.apertures:
  7951. if obj.apertures[apid]['type'] == 'C':
  7952. header += "%ADD{apid}{type},{size}*%\n".format(
  7953. apid=str(apid),
  7954. type='C',
  7955. size=(factor * obj.apertures[apid]['size'])
  7956. )
  7957. elif obj.apertures[apid]['type'] == 'R':
  7958. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7959. apid=str(apid),
  7960. type='R',
  7961. width=(factor * obj.apertures[apid]['width']),
  7962. height=(factor * obj.apertures[apid]['height'])
  7963. )
  7964. elif obj.apertures[apid]['type'] == 'O':
  7965. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7966. apid=str(apid),
  7967. type='O',
  7968. width=(factor * obj.apertures[apid]['width']),
  7969. height=(factor * obj.apertures[apid]['height'])
  7970. )
  7971. header += '\n'
  7972. # obsolete units but some software may need it
  7973. if gunits == 'IN':
  7974. header += 'G70*\n'
  7975. else:
  7976. header += 'G71*\n'
  7977. # Absolute Mode
  7978. header += 'G90*\n'
  7979. header += 'G01*\n'
  7980. # positive polarity
  7981. header += '%LPD*%\n'
  7982. footer = 'M02*\n'
  7983. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7984. exported_gerber = header
  7985. exported_gerber += gerber_code
  7986. exported_gerber += footer
  7987. if local_use is None:
  7988. try:
  7989. with open(filename, 'w') as fp:
  7990. fp.write(exported_gerber)
  7991. except PermissionError:
  7992. self.inform.emit('[WARNING] %s' %
  7993. _("Permission denied, saving not possible.\n"
  7994. "Most likely another app is holding the file open and not accessible."))
  7995. return 'fail'
  7996. if self.defaults["global_open_style"] is False:
  7997. self.file_opened.emit("Gerber", filename)
  7998. self.file_saved.emit("Gerber", filename)
  7999. self.inform.emit('[success] %s: %s' %
  8000. (_("Gerber file exported to"), filename))
  8001. else:
  8002. return exported_gerber
  8003. except Exception as e:
  8004. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8005. return 'fail'
  8006. if use_thread is True:
  8007. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8008. def job_thread_grb(app_obj):
  8009. ret = make_gerber()
  8010. if ret == 'fail':
  8011. self.inform.emit('[ERROR_NOTCL] %s' %
  8012. _('Could not export Gerber file.'))
  8013. return
  8014. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8015. else:
  8016. ret = make_gerber()
  8017. if ret == 'fail':
  8018. self.inform.emit('[ERROR_NOTCL] %s' %
  8019. _('Could not export Gerber file.'))
  8020. return 'fail'
  8021. if local_use is not None:
  8022. return ret
  8023. def export_dxf(self, obj_name, filename, use_thread=True):
  8024. """
  8025. Exports a Geometry Object to an DXF file.
  8026. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8027. :param filename: Path to the DXF file to save to.
  8028. :param use_thread: if to be run in a separate thread
  8029. :return:
  8030. """
  8031. self.report_usage("export_dxf()")
  8032. if filename is None:
  8033. filename = self.defaults["global_last_save_folder"]
  8034. self.log.debug("export_dxf()")
  8035. format_exc = ''
  8036. units = ''
  8037. try:
  8038. obj = self.collection.get_by_name(str(obj_name))
  8039. except:
  8040. # TODO: The return behavior has not been established... should raise exception?
  8041. return "Could not retrieve object: %s" % obj_name
  8042. # updated units
  8043. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8044. if units == 'IN' or units == 'INCH':
  8045. units = 'INCH'
  8046. elif units == 'MM' or units == 'METIRC':
  8047. units ='METRIC'
  8048. def make_dxf():
  8049. try:
  8050. dxf_code = obj.export_dxf()
  8051. dxf_code.saveas(filename)
  8052. if self.defaults["global_open_style"] is False:
  8053. self.file_opened.emit("DXF", filename)
  8054. self.file_saved.emit("DXF", filename)
  8055. self.inform.emit('[success] %s: %s' %
  8056. (_("DXF file exported to"), filename))
  8057. except:
  8058. return 'fail'
  8059. if use_thread is True:
  8060. with self.proc_container.new(_("Exporting DXF")) as proc:
  8061. def job_thread_exc(app_obj):
  8062. ret = make_dxf()
  8063. if ret == 'fail':
  8064. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8065. _('Could not export DXF file.'))
  8066. return
  8067. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8068. else:
  8069. ret = make_dxf()
  8070. if ret == 'fail':
  8071. self.inform.emit('[WARNING_NOTCL] %s' %
  8072. _('Could not export DXF file.'))
  8073. return
  8074. def import_svg(self, filename, geo_type='geometry', outname=None):
  8075. """
  8076. Adds a new Geometry Object to the projects and populates
  8077. it with shapes extracted from the SVG file.
  8078. :param filename: Path to the SVG file.
  8079. :param outname:
  8080. :return:
  8081. """
  8082. self.report_usage("import_svg()")
  8083. obj_type = ""
  8084. if geo_type is None or geo_type == "geometry":
  8085. obj_type = "geometry"
  8086. elif geo_type == "gerber":
  8087. obj_type = geo_type
  8088. else:
  8089. self.inform.emit('[ERROR_NOTCL] %s' %
  8090. _("Not supported type is picked as parameter. "
  8091. "Only Geometry and Gerber are supported"))
  8092. return
  8093. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8094. def obj_init(geo_obj, app_obj):
  8095. geo_obj.import_svg(filename, obj_type, units=units)
  8096. geo_obj.multigeo = False
  8097. with self.proc_container.new(_("Importing SVG")) as proc:
  8098. # Object name
  8099. name = outname or filename.split('/')[-1].split('\\')[-1]
  8100. self.new_object(obj_type, name, obj_init, autoselected=False)
  8101. self.progress.emit(20)
  8102. # Register recent file
  8103. self.file_opened.emit("svg", filename)
  8104. # GUI feedback
  8105. self.inform.emit('[success] %s: %s' %
  8106. (_("Opened"), filename))
  8107. self.progress.emit(100)
  8108. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8109. """
  8110. Adds a new Geometry Object to the projects and populates
  8111. it with shapes extracted from the DXF file.
  8112. :param filename: Path to the DXF file.
  8113. :param outname:
  8114. :type putname: str
  8115. :return:
  8116. """
  8117. self.report_usage("import_dxf()")
  8118. obj_type = ""
  8119. if geo_type is None or geo_type == "geometry":
  8120. obj_type = "geometry"
  8121. elif geo_type == "gerber":
  8122. obj_type = geo_type
  8123. else:
  8124. self.inform.emit('[ERROR_NOTCL] %s' %
  8125. _("Not supported type is picked as parameter. "
  8126. "Only Geometry and Gerber are supported"))
  8127. return
  8128. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8129. def obj_init(geo_obj, app_obj):
  8130. geo_obj.import_dxf(filename, obj_type, units=units)
  8131. geo_obj.multigeo = False
  8132. with self.proc_container.new(_("Importing DXF")) as proc:
  8133. # Object name
  8134. name = outname or filename.split('/')[-1].split('\\')[-1]
  8135. self.new_object(obj_type, name, obj_init, autoselected=False)
  8136. self.progress.emit(20)
  8137. # Register recent file
  8138. self.file_opened.emit("dxf", filename)
  8139. # GUI feedback
  8140. self.inform.emit('[success] %s: %s' %
  8141. (_("Opened"), filename))
  8142. self.progress.emit(100)
  8143. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8144. """
  8145. Adds a new Geometry Object to the projects and populates
  8146. it with shapes extracted from the SVG file.
  8147. :param filename: Path to the SVG file.
  8148. :param o_type: type of FlatCAM objeect
  8149. :param dpi: dot per inch
  8150. :param mode: black or color
  8151. :param mask: dictate the level of detail
  8152. :param outname: name for the resulting file
  8153. :return:
  8154. """
  8155. self.report_usage("import_image()")
  8156. if o_type is None or o_type == "geometry":
  8157. obj_type = "geometry"
  8158. elif o_type == "gerber":
  8159. obj_type = o_type
  8160. else:
  8161. self.inform.emit('[ERROR_NOTCL] %s' %
  8162. _("Not supported type is picked as parameter. "
  8163. "Only Geometry and Gerber are supported"))
  8164. return
  8165. def obj_init(geo_obj, app_obj):
  8166. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8167. geo_obj.multigeo = False
  8168. with self.proc_container.new(_("Importing Image")) as proc:
  8169. # Object name
  8170. name = outname or filename.split('/')[-1].split('\\')[-1]
  8171. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8172. self.new_object(obj_type, name, obj_init)
  8173. self.progress.emit(20)
  8174. # Register recent file
  8175. self.file_opened.emit("image", filename)
  8176. # GUI feedback
  8177. self.inform.emit('[success] %s: %s' %
  8178. (_("Opened"), filename))
  8179. self.progress.emit(100)
  8180. def open_gerber(self, filename, outname=None):
  8181. """
  8182. Opens a Gerber file, parses it and creates a new object for
  8183. it in the program. Thread-safe.
  8184. :param outname: Name of the resulting object. None causes the
  8185. name to be that of the file.
  8186. :param filename: Gerber file filename
  8187. :type filename: str
  8188. :param follow: If true, the parser will not create polygons, just lines
  8189. following the gerber path.
  8190. :type follow: bool
  8191. :return: None
  8192. """
  8193. # How the object should be initialized
  8194. def obj_init(gerber_obj, app_obj):
  8195. assert isinstance(gerber_obj, FlatCAMGerber), \
  8196. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8197. # Opening the file happens here
  8198. self.progress.emit(30)
  8199. try:
  8200. gerber_obj.parse_file(filename)
  8201. except IOError:
  8202. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8203. (_("Failed to open file"), filename))
  8204. app_obj.progress.emit(0)
  8205. return "fail"
  8206. except ParseError as err:
  8207. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8208. (_("Failed to parse file"), filename, str(err)))
  8209. app_obj.progress.emit(0)
  8210. self.log.error(str(err))
  8211. return "fail"
  8212. except Exception as e:
  8213. log.debug("App.open_gerber() --> %s" % str(e))
  8214. msg = '[ERROR] %s' % \
  8215. _("An internal error has occurred. See shell.\n")
  8216. msg += traceback.format_exc()
  8217. app_obj.inform.emit(msg)
  8218. return "fail"
  8219. if gerber_obj.is_empty():
  8220. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8221. # self.collection.set_active(gerber_obj.options["name"])
  8222. # self.collection.delete_active()
  8223. self.inform.emit('[ERROR_NOTCL] %s' %
  8224. _("Object is not Gerber file or empty. Aborting object creation."))
  8225. return "fail"
  8226. # Further parsing
  8227. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8228. App.log.debug("open_gerber()")
  8229. with self.proc_container.new(_("Opening Gerber")) as proc:
  8230. self.progress.emit(10)
  8231. # Object name
  8232. name = outname or filename.split('/')[-1].split('\\')[-1]
  8233. # # ## Object creation # ##
  8234. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8235. if ret == 'fail':
  8236. self.inform.emit('[ERROR_NOTCL]%s' %
  8237. _(' Open Gerber failed. Probable not a Gerber file.'))
  8238. return
  8239. # Register recent file
  8240. self.file_opened.emit("gerber", filename)
  8241. self.progress.emit(100)
  8242. # GUI feedback
  8243. self.inform.emit('[success] %s: %s' %
  8244. (_("Opened"), filename))
  8245. def open_excellon(self, filename, outname=None, plot=True):
  8246. """
  8247. Opens an Excellon file, parses it and creates a new object for
  8248. it in the program. Thread-safe.
  8249. :param outname: Name of the resulting object. None causes the
  8250. name to be that of the file.
  8251. :param filename: Excellon file filename
  8252. :type filename: str
  8253. :return: None
  8254. """
  8255. App.log.debug("open_excellon()")
  8256. # How the object should be initialized
  8257. def obj_init(excellon_obj, app_obj):
  8258. # self.progress.emit(20)
  8259. try:
  8260. ret = excellon_obj.parse_file(filename=filename)
  8261. if ret == "fail":
  8262. log.debug("Excellon parsing failed.")
  8263. self.inform.emit('[ERROR_NOTCL] %s' %
  8264. _("This is not Excellon file."))
  8265. return "fail"
  8266. except IOError:
  8267. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8268. (_("Cannot open file"), filename))
  8269. log.debug("Could not open Excellon object.")
  8270. self.progress.emit(0) # TODO: self and app_bjj mixed
  8271. return "fail"
  8272. except:
  8273. msg = '[ERROR_NOTCL] %s' % \
  8274. _("An internal error has occurred. See shell.\n")
  8275. msg += traceback.format_exc()
  8276. app_obj.inform.emit(msg)
  8277. return "fail"
  8278. ret = excellon_obj.create_geometry()
  8279. if ret == 'fail':
  8280. log.debug("Could not create geometry for Excellon object.")
  8281. return "fail"
  8282. for tool in excellon_obj.tools:
  8283. if excellon_obj.tools[tool]['solid_geometry']:
  8284. return
  8285. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8286. (_("No geometry found in file"), filename))
  8287. return "fail"
  8288. with self.proc_container.new(_("Opening Excellon.")):
  8289. # Object name
  8290. name = outname or filename.split('/')[-1].split('\\')[-1]
  8291. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8292. if ret_val == 'fail':
  8293. self.inform.emit('[ERROR_NOTCL] %s' %
  8294. _('Open Excellon file failed. Probable not an Excellon file.'))
  8295. return
  8296. # Register recent file
  8297. self.file_opened.emit("excellon", filename)
  8298. # GUI feedback
  8299. self.inform.emit('[success] %s: %s' %
  8300. (_("Opened"), filename))
  8301. def open_gcode(self, filename, outname=None, plot=True):
  8302. """
  8303. Opens a G-gcode file, parses it and creates a new object for
  8304. it in the program. Thread-safe.
  8305. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8306. :param filename: G-code file filename
  8307. :type filename: str
  8308. :return: None
  8309. """
  8310. App.log.debug("open_gcode()")
  8311. # How the object should be initialized
  8312. def obj_init(job_obj, app_obj_):
  8313. """
  8314. :param job_obj: the resulting object
  8315. :type app_obj_: App
  8316. """
  8317. assert isinstance(app_obj_, App), \
  8318. "Initializer expected App, got %s" % type(app_obj_)
  8319. self.progress.emit(10)
  8320. try:
  8321. f = open(filename)
  8322. gcode = f.read()
  8323. f.close()
  8324. except IOError:
  8325. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8326. (_("Failed to open"), filename))
  8327. self.progress.emit(0)
  8328. return "fail"
  8329. job_obj.gcode = gcode
  8330. self.progress.emit(20)
  8331. ret = job_obj.gcode_parse()
  8332. if ret == "fail":
  8333. self.inform.emit('[ERROR_NOTCL] %s' %
  8334. _("This is not GCODE"))
  8335. return "fail"
  8336. self.progress.emit(60)
  8337. job_obj.create_geometry()
  8338. with self.proc_container.new(_("Opening G-Code.")):
  8339. # Object name
  8340. name = outname or filename.split('/')[-1].split('\\')[-1]
  8341. # New object creation and file processing
  8342. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8343. if ret == 'fail':
  8344. self.inform.emit('[ERROR_NOTCL] %s' %
  8345. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8346. "Attempting to create a FlatCAM CNCJob Object from "
  8347. "G-Code file failed during processing"))
  8348. return "fail"
  8349. # Register recent file
  8350. self.file_opened.emit("cncjob", filename)
  8351. # GUI feedback
  8352. self.inform.emit('[success] %s: %s' %
  8353. (_("Opened"), filename))
  8354. self.progress.emit(100)
  8355. def open_config_file(self, filename, run_from_arg=None):
  8356. """
  8357. Loads a config file from the specified file.
  8358. :param filename: Name of the file from which to load.
  8359. :type filename: str
  8360. :return: None
  8361. """
  8362. App.log.debug("Opening config file: " + filename)
  8363. if run_from_arg:
  8364. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8365. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8366. _("Opening FlatCAM Config file.")),
  8367. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8368. color=QtGui.QColor("gray"))
  8369. # add the tab if it was closed
  8370. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8371. # first clear previous text in text editor (if any)
  8372. self.ui.code_editor.clear()
  8373. # Switch plot_area to CNCJob tab
  8374. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8375. try:
  8376. if filename:
  8377. f = QtCore.QFile(filename)
  8378. if f.open(QtCore.QIODevice.ReadOnly):
  8379. stream = QtCore.QTextStream(f)
  8380. gcode_edited = stream.readAll()
  8381. self.ui.code_editor.setPlainText(gcode_edited)
  8382. f.close()
  8383. except IOError:
  8384. App.log.error("Failed to open config file: %s" % filename)
  8385. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8386. (_("Failed to open config file"), filename))
  8387. return
  8388. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8389. """
  8390. Loads a project from the specified file.
  8391. 1) Loads and parses file
  8392. 2) Registers the file as recently opened.
  8393. 3) Calls on_file_new()
  8394. 4) Updates options
  8395. 5) Calls new_object() with the object's from_dict() as init method.
  8396. 6) Calls plot_all() if plot=True
  8397. :param filename: Name of the file from which to load.
  8398. :type filename: str
  8399. :param run_from_arg: True if run for arguments
  8400. :param plot: If True plot all objects in the project
  8401. :param cli: run from command line
  8402. :return: None
  8403. """
  8404. App.log.debug("Opening project: " + filename)
  8405. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8406. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8407. if cli is None:
  8408. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8409. if run_from_arg:
  8410. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8411. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8412. _("Opening FlatCAM Project file.")),
  8413. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8414. color=QtGui.QColor("gray"))
  8415. # Open and parse an uncompressed Project file
  8416. try:
  8417. f = open(filename, 'r')
  8418. except IOError:
  8419. App.log.error("Failed to open project file: %s" % filename)
  8420. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8421. (_("Failed to open project file"), filename))
  8422. return
  8423. try:
  8424. d = json.load(f, object_hook=dict2obj)
  8425. except Exception as e:
  8426. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8427. (filename, str(e)))
  8428. f.close()
  8429. # Open and parse a compressed Project file
  8430. try:
  8431. with lzma.open(filename) as f:
  8432. file_content = f.read().decode('utf-8')
  8433. d = json.loads(file_content, object_hook=dict2obj)
  8434. except Exception as e:
  8435. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8436. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8437. (_("Failed to open project file"), filename))
  8438. return
  8439. # Clear the current project
  8440. # # NOT THREAD SAFE # ##
  8441. if run_from_arg is True:
  8442. pass
  8443. elif cli is True:
  8444. self.delete_selection_shape()
  8445. else:
  8446. self.on_file_new()
  8447. # Project options
  8448. self.options.update(d['options'])
  8449. self.project_filename = filename
  8450. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8451. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8452. if cli is None:
  8453. self.set_screen_units(self.options["units"])
  8454. # Re create objects
  8455. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8456. for obj in d['objs']:
  8457. def obj_init(obj_inst, app_inst):
  8458. obj_inst.from_dict(obj)
  8459. App.log.debug("Recreating from opened project an %s object: %s" %
  8460. (obj['kind'].capitalize(), obj['options']['name']))
  8461. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8462. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8463. if cli is None:
  8464. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8465. obj['kind'].upper(),
  8466. obj['options']['name']
  8467. )
  8468. )
  8469. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8470. self.inform.emit('[success] %s: %s' %
  8471. (_("Project loaded from"), filename))
  8472. self.should_we_save = False
  8473. self.file_opened.emit("project", filename)
  8474. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8475. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8476. if cli is None:
  8477. self.set_ui_title(name=self.project_filename)
  8478. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8479. def propagate_defaults(self, silent=False):
  8480. """
  8481. This method is used to set default values in classes. It's
  8482. an alternative to project options but allows the use
  8483. of values invisible to the user.
  8484. :return: None
  8485. """
  8486. if silent is False:
  8487. self.log.debug("propagate_defaults()")
  8488. # Which objects to update the given parameters.
  8489. routes = {
  8490. "global_zdownrate": CNCjob,
  8491. "excellon_zeros": Excellon,
  8492. "excellon_format_upper_in": Excellon,
  8493. "excellon_format_lower_in": Excellon,
  8494. "excellon_format_upper_mm": Excellon,
  8495. "excellon_format_lower_mm": Excellon,
  8496. "excellon_units": Excellon,
  8497. "gerber_use_buffer_for_union": Gerber,
  8498. "geometry_multidepth": Geometry
  8499. }
  8500. for param in routes:
  8501. if param in routes[param].defaults:
  8502. try:
  8503. routes[param].defaults[param] = self.defaults[param]
  8504. if silent is False:
  8505. self.log.debug(" " + param + " OK")
  8506. except KeyError:
  8507. if silent is False:
  8508. self.log.debug(" ERROR: " + param + " not in defaults.")
  8509. else:
  8510. # Try extracting the name:
  8511. # classname_param here is param in the object
  8512. if param.find(routes[param].__name__.lower() + "_") == 0:
  8513. p = param[len(routes[param].__name__) + 1:]
  8514. if p in routes[param].defaults:
  8515. routes[param].defaults[p] = self.defaults[param]
  8516. if silent is False:
  8517. self.log.debug(" " + param + " OK!")
  8518. def restore_main_win_geom(self):
  8519. try:
  8520. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8521. self.defaults["global_def_win_y"],
  8522. self.defaults["global_def_win_w"],
  8523. self.defaults["global_def_win_h"])
  8524. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8525. except KeyError as e:
  8526. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8527. def plot_all(self, zoom=True):
  8528. """
  8529. Re-generates all plots from all objects.
  8530. :return: None
  8531. """
  8532. self.log.debug("Plot_all()")
  8533. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8534. for obj in self.collection.get_list():
  8535. def worker_task(obj):
  8536. with self.proc_container.new("Plotting"):
  8537. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8538. if zoom:
  8539. self.object_plotted.emit(obj)
  8540. # Send to worker
  8541. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8542. def register_folder(self, filename):
  8543. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8544. def register_save_folder(self, filename):
  8545. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8546. def set_progress_bar(self, percentage, text=""):
  8547. self.ui.progress_bar.setValue(int(percentage))
  8548. def setup_shell(self):
  8549. """
  8550. Creates shell functions. Runs once at startup.
  8551. :return: None
  8552. """
  8553. self.log.debug("setup_shell()")
  8554. def shelp(p=None):
  8555. if not p:
  8556. return _("Available commands:\n") + \
  8557. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8558. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8559. if p not in commands:
  8560. return "Unknown command: %s" % p
  8561. return commands[p]["help"]
  8562. # --- Migrated to new architecture ---
  8563. # def options(name):
  8564. # ops = self.collection.get_by_name(str(name)).options
  8565. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8566. def h(*args):
  8567. """
  8568. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8569. and standalone parameters into list.
  8570. """
  8571. kwa = {}
  8572. a = []
  8573. n = len(args)
  8574. name = None
  8575. for i in range(n):
  8576. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8577. if match:
  8578. assert name is None
  8579. name = match.group(1)
  8580. continue
  8581. if name is None:
  8582. a.append(args[i])
  8583. else:
  8584. kwa[name] = args[i]
  8585. name = None
  8586. return a, kwa
  8587. @contextmanager
  8588. def wait_signal(signal, timeout=10000):
  8589. """
  8590. Block loop until signal emitted, timeout (ms) elapses
  8591. or unhandled exception happens in a thread.
  8592. :param timeout: time after which the loop is exited
  8593. :param signal: Signal to wait for.
  8594. """
  8595. loop = QtCore.QEventLoop()
  8596. # Normal termination
  8597. signal.connect(loop.quit)
  8598. # Termination by exception in thread
  8599. self.thread_exception.connect(loop.quit)
  8600. status = {'timed_out': False}
  8601. def report_quit():
  8602. status['timed_out'] = True
  8603. loop.quit()
  8604. yield
  8605. # Temporarily change how exceptions are managed.
  8606. oeh = sys.excepthook
  8607. ex = []
  8608. def except_hook(type_, value, traceback_):
  8609. ex.append(value)
  8610. oeh(type_, value, traceback_)
  8611. sys.excepthook = except_hook
  8612. # Terminate on timeout
  8613. if timeout is not None:
  8614. QtCore.QTimer.singleShot(timeout, report_quit)
  8615. # # ## Block ## ##
  8616. loop.exec_()
  8617. # Restore exception management
  8618. sys.excepthook = oeh
  8619. if ex:
  8620. self.raiseTclError(str(ex[0]))
  8621. if status['timed_out']:
  8622. raise Exception('Timed out!')
  8623. def make_docs():
  8624. output = ''
  8625. import collections
  8626. od = collections.OrderedDict(sorted(commands.items()))
  8627. for cmd_, val in od.items():
  8628. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8629. t = val['help']
  8630. usage_i = t.find('>')
  8631. if usage_i < 0:
  8632. expl = t
  8633. output += expl + '\n\n'
  8634. continue
  8635. expl = t[:usage_i - 1]
  8636. output += expl + '\n\n'
  8637. end_usage_i = t[usage_i:].find('\n')
  8638. if end_usage_i < 0:
  8639. end_usage_i = len(t[usage_i:])
  8640. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8641. else:
  8642. extras = t[usage_i+end_usage_i+1:]
  8643. parts = [s.strip() for s in extras.split('\n')]
  8644. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8645. for p in parts:
  8646. output += ' ' + p + '\n\n'
  8647. return output
  8648. '''
  8649. Howto implement TCL shell commands:
  8650. All parameters passed to command should be possible to set as None and test it afterwards.
  8651. This is because we need to see error caused in tcl,
  8652. if None value as default parameter is not allowed TCL will return empty error.
  8653. Use:
  8654. def mycommand(name=None,...):
  8655. Test it like this:
  8656. if name is None:
  8657. self.raise_tcl_error('Argument name is missing.')
  8658. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8659. otherwise we will miss it and processing will silently continue.
  8660. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8661. which is catched in exec_command and displayed in TCL shell console with red background.
  8662. Error in console is displayed with TCL trace.
  8663. This behavior works only within main thread,
  8664. errors with promissed tasks can be catched and detected only with log.
  8665. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8666. TCL shell.
  8667. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8668. '''
  8669. commands = {
  8670. 'help': {
  8671. 'fcn': shelp,
  8672. 'help': _("Shows list of commands.")
  8673. },
  8674. }
  8675. # Import/overwrite tcl commands as objects of TclCommand descendants
  8676. # This modifies the variable 'commands'.
  8677. tclCommands.register_all_commands(self, commands)
  8678. # Add commands to the tcl interpreter
  8679. for cmd in commands:
  8680. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8681. # Make the tcl puts function return instead of print to stdout
  8682. self.tcl.eval('''
  8683. rename puts original_puts
  8684. proc puts {args} {
  8685. if {[llength $args] == 1} {
  8686. return "[lindex $args 0]"
  8687. } else {
  8688. eval original_puts $args
  8689. }
  8690. }
  8691. ''')
  8692. def setup_recent_items(self):
  8693. # TODO: Move this to constructor
  8694. icons = {
  8695. "gerber": "share/flatcam_icon16.png",
  8696. "excellon": "share/drill16.png",
  8697. 'geometry': "share/geometry16.png",
  8698. "cncjob": "share/cnc16.png",
  8699. "project": "share/project16.png",
  8700. "svg": "share/geometry16.png",
  8701. "dxf": "share/dxf16.png",
  8702. "pdf": "share/pdf32.png",
  8703. "image": "share/image16.png"
  8704. }
  8705. openers = {
  8706. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8707. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8708. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8709. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8710. 'project': self.open_project,
  8711. 'svg': self.import_svg,
  8712. 'dxf': self.import_dxf,
  8713. 'image': self.import_image,
  8714. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8715. }
  8716. # Open recent file for files
  8717. try:
  8718. f = open(self.data_path + '/recent.json')
  8719. except IOError:
  8720. App.log.error("Failed to load recent item list.")
  8721. self.inform.emit('[ERROR_NOTCL] %s' %
  8722. _("Failed to load recent item list."))
  8723. return
  8724. try:
  8725. self.recent = json.load(f)
  8726. except json.scanner.JSONDecodeError:
  8727. App.log.error("Failed to parse recent item list.")
  8728. self.inform.emit('[ERROR_NOTCL] %s' %
  8729. _("Failed to parse recent item list."))
  8730. f.close()
  8731. return
  8732. f.close()
  8733. # Open recent file for projects
  8734. try:
  8735. fp = open(self.data_path + '/recent_projects.json')
  8736. except IOError:
  8737. App.log.error("Failed to load recent project item list.")
  8738. self.inform.emit('[ERROR_NOTCL] %s' %
  8739. _("Failed to load recent projects item list."))
  8740. return
  8741. try:
  8742. self.recent_projects = json.load(fp)
  8743. except json.scanner.JSONDecodeError:
  8744. App.log.error("Failed to parse recent project item list.")
  8745. self.inform.emit('[ERROR_NOTCL] %s' %
  8746. _("Failed to parse recent project item list."))
  8747. fp.close()
  8748. return
  8749. fp.close()
  8750. # Closure needed to create callbacks in a loop.
  8751. # Otherwise late binding occurs.
  8752. def make_callback(func, fname):
  8753. def opener():
  8754. func(fname)
  8755. return opener
  8756. def reset_recent_files():
  8757. # Reset menu
  8758. self.ui.recent.clear()
  8759. self.recent = []
  8760. try:
  8761. f = open(self.data_path + '/recent.json', 'w')
  8762. except IOError:
  8763. App.log.error("Failed to open recent items file for writing.")
  8764. return
  8765. json.dump(self.recent, f)
  8766. def reset_recent_projects():
  8767. # Reset menu
  8768. self.ui.recent_projects.clear()
  8769. self.recent_projects = []
  8770. try:
  8771. fp = open(self.data_path + '/recent_projects.json', 'w')
  8772. except IOError:
  8773. App.log.error("Failed to open recent projects items file for writing.")
  8774. return
  8775. json.dump(self.recent, fp)
  8776. # Reset menu
  8777. self.ui.recent.clear()
  8778. self.ui.recent_projects.clear()
  8779. # Create menu items for projects
  8780. for recent in self.recent_projects:
  8781. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8782. if recent['kind'] == 'project':
  8783. try:
  8784. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8785. # Attach callback
  8786. o = make_callback(openers[recent["kind"]], recent['filename'])
  8787. action.triggered.connect(o)
  8788. self.ui.recent_projects.addAction(action)
  8789. except KeyError:
  8790. App.log.error("Unsupported file type: %s" % recent["kind"])
  8791. # Last action in Recent Files menu is one that Clear the content
  8792. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8793. clear_action_proj.triggered.connect(reset_recent_projects)
  8794. self.ui.recent_projects.addSeparator()
  8795. self.ui.recent_projects.addAction(clear_action_proj)
  8796. # Create menu items for files
  8797. for recent in self.recent:
  8798. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8799. if recent['kind'] != 'project':
  8800. try:
  8801. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8802. # Attach callback
  8803. o = make_callback(openers[recent["kind"]], recent['filename'])
  8804. action.triggered.connect(o)
  8805. self.ui.recent.addAction(action)
  8806. except KeyError:
  8807. App.log.error("Unsupported file type: %s" % recent["kind"])
  8808. # Last action in Recent Files menu is one that Clear the content
  8809. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8810. clear_action.triggered.connect(reset_recent_files)
  8811. self.ui.recent.addSeparator()
  8812. self.ui.recent.addAction(clear_action)
  8813. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8814. # self.ui.menufilerecent.set_submenu(recent_menu)
  8815. # recent_menu.show_all()
  8816. # self.ui.recent.show()
  8817. self.log.debug("Recent items list has been populated.")
  8818. def setup_component_editor(self):
  8819. # label = QtWidgets.QLabel("Choose an item from Project")
  8820. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8821. sel_title = QtWidgets.QTextEdit(
  8822. _('<b>Shortcut Key List</b>'))
  8823. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8824. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8825. settings = QSettings("Open Source", "FlatCAM")
  8826. if settings.contains("notebook_font_size"):
  8827. fsize = settings.value('notebook_font_size', type=int)
  8828. else:
  8829. fsize = 12
  8830. tsize = fsize + int(fsize / 2)
  8831. # selected_text = (_('''
  8832. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8833. #
  8834. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8835. # The normal flow when working in FlatCAM is the following:</span></p>
  8836. #
  8837. # <ol>
  8838. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8839. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8840. # even dragging and dropping the files on the GUI.<br />
  8841. # <br />
  8842. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  8843. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8844. # &nbsp;</li>
  8845. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  8846. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8847. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8848. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8849. # <br />
  8850. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  8851. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8852. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8853. # it even if it was out of focus.<br />
  8854. # <br />
  8855. # You can change the parameters in this screen and the flow direction is like this:<br />
  8856. # <br />
  8857. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  8858. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8859. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8860. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8861. # </ol>
  8862. #
  8863. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8864. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8865. # <strong>F3</strong>.</span></p>
  8866. #
  8867. # ''').format(fsize=fsize, tsize=tsize))
  8868. selected_text = '''
  8869. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  8870. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  8871. %s:</span></p>
  8872. <ol>
  8873. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  8874. <br />
  8875. %s &amp; %s.</span><br />
  8876. &nbsp;</li>
  8877. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  8878. <br />
  8879. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  8880. <br />
  8881. %s:<br />
  8882. <br />
  8883. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  8884. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  8885. </ol>
  8886. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  8887. <strong>F3</strong>.</span></p>
  8888. ''' % (
  8889. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  8890. _("The normal flow when working in FlatCAM is the following"),
  8891. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  8892. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  8893. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  8894. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  8895. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  8896. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  8897. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  8898. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  8899. _("If the selection of the object is done on the canvas by single click instead, and the"),
  8900. _("SELECTED TAB"),
  8901. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  8902. "double clicking on the object on the canvas will bring the"),
  8903. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  8904. _("You can change the parameters in this screen and the flow direction is like this"),
  8905. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  8906. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  8907. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  8908. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  8909. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  8910. )
  8911. sel_title.setText(selected_text)
  8912. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8913. self.ui.selected_scroll_area.setWidget(sel_title)
  8914. def setup_obj_classes(self):
  8915. """
  8916. Sets up application specifics on the FlatCAMObj class.
  8917. :return: None
  8918. """
  8919. FlatCAMObj.app = self
  8920. ObjectCollection.app = self
  8921. Gerber.app = self
  8922. Excellon.app = self
  8923. Geometry.app = self
  8924. CNCjob.app = self
  8925. FCProcess.app = self
  8926. FCProcessContainer.app = self
  8927. def version_check(self):
  8928. """
  8929. Checks for the latest version of the program. Alerts the
  8930. user if theirs is outdated. This method is meant to be run
  8931. in a separate thread.
  8932. :return: None
  8933. """
  8934. self.log.debug("version_check()")
  8935. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8936. full_url = App.version_url + \
  8937. "?s=" + str(self.defaults['global_serial']) + \
  8938. "&v=" + str(self.version) + \
  8939. "&os=" + str(self.os) + \
  8940. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8941. else:
  8942. # no_stats dict; just so it won't break things on website
  8943. no_ststs_dict = {}
  8944. no_ststs_dict["global_ststs"] = {}
  8945. full_url = App.version_url + \
  8946. "?s=" + str(self.defaults['global_serial']) + \
  8947. "&v=" + str(self.version) + \
  8948. "&os=" + str(self.os) + \
  8949. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8950. App.log.debug("Checking for updates @ %s" % full_url)
  8951. # ## Get the data
  8952. try:
  8953. f = urllib.request.urlopen(full_url)
  8954. except:
  8955. # App.log.warning("Failed checking for latest version. Could not connect.")
  8956. self.log.warning("Failed checking for latest version. Could not connect.")
  8957. self.inform.emit('[WARNING_NOTCL] %s' %
  8958. _("Failed checking for latest version. Could not connect."))
  8959. return
  8960. try:
  8961. data = json.load(f)
  8962. except Exception as e:
  8963. App.log.error("Could not parse information about latest version.")
  8964. self.inform.emit('[ERROR_NOTCL] %s' %
  8965. _("Could not parse information about latest version."))
  8966. App.log.debug("json.load(): %s" % str(e))
  8967. f.close()
  8968. return
  8969. f.close()
  8970. # ## Latest version?
  8971. if self.version >= data["version"]:
  8972. App.log.debug("FlatCAM is up to date!")
  8973. self.inform.emit('[success] %s' %
  8974. _("FlatCAM is up to date!"))
  8975. return
  8976. App.log.debug("Newer version available.")
  8977. self.message.emit(
  8978. _("Newer Version Available"),
  8979. _("There is a newer version of FlatCAM available for download:\n\n") +
  8980. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8981. _("info")
  8982. )
  8983. def on_plotcanvas_setup(self, container=None):
  8984. """
  8985. This is doing the setup for the plot area (VisPy canvas)
  8986. :param container: widget where to install the canvas
  8987. :return: None
  8988. """
  8989. if container:
  8990. plot_container = container
  8991. else:
  8992. plot_container = self.ui.right_layout
  8993. self.plotcanvas = PlotCanvas(plot_container, self)
  8994. # So it can receive key presses
  8995. self.plotcanvas.native.setFocus()
  8996. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8997. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8998. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8999. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  9000. # Keys over plot enabled
  9001. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  9002. self.app_cursor = self.plotcanvas.new_cursor()
  9003. self.app_cursor.enabled = False
  9004. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9005. def on_zoom_fit(self, event):
  9006. """
  9007. Callback for zoom-out request. This can be either from the corresponding
  9008. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9009. with axes limits from the geometry bounds of all objects.
  9010. :param event: Ignored.
  9011. :return: None
  9012. """
  9013. self.plotcanvas.fit_view()
  9014. def on_zoom_in(self):
  9015. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9016. def on_zoom_out(self):
  9017. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9018. def disable_all_plots(self):
  9019. self.report_usage("disable_all_plots()")
  9020. self.disable_plots(self.collection.get_list())
  9021. self.inform.emit('[success] %s' %
  9022. _("All plots disabled."))
  9023. def disable_other_plots(self):
  9024. self.report_usage("disable_other_plots()")
  9025. self.disable_plots(self.collection.get_non_selected())
  9026. self.inform.emit('[success] %s' %
  9027. _("All non selected plots disabled."))
  9028. def enable_all_plots(self):
  9029. self.report_usage("enable_all_plots()")
  9030. self.enable_plots(self.collection.get_list())
  9031. self.inform.emit('[success] %s' %
  9032. _("All plots enabled."))
  9033. def on_enable_sel_plots(self):
  9034. log.debug("App.on_enable_sel_plot()")
  9035. object_list = self.collection.get_selected()
  9036. self.enable_plots(objects=object_list)
  9037. self.inform.emit('[success] %s' %
  9038. _("Selected plots enabled..."))
  9039. def on_disable_sel_plots(self):
  9040. log.debug("App.on_disable_sel_plot()")
  9041. # self.inform.emit(_("Disabling plots ..."))
  9042. object_list = self.collection.get_selected()
  9043. self.disable_plots(objects=object_list)
  9044. self.inform.emit('[success] %s' %
  9045. _("Selected plots disabled..."))
  9046. def enable_plots(self, objects):
  9047. """
  9048. Disables plots
  9049. :param objects: list of Objects to be enabled
  9050. :return:
  9051. """
  9052. log.debug("Enabling plots ...")
  9053. # self.inform.emit(_("Working ..."))
  9054. for obj in objects:
  9055. if obj.options['plot'] is False:
  9056. obj.options.set_change_callback(lambda x: None)
  9057. obj.options['plot'] = True
  9058. obj.options.set_change_callback(obj.on_options_change)
  9059. def worker_task(objects):
  9060. with self.proc_container.new(_("Enabling plots ...")):
  9061. for obj in objects:
  9062. # obj.options['plot'] = True
  9063. if isinstance(obj, FlatCAMCNCjob):
  9064. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9065. else:
  9066. obj.plot(visible=True)
  9067. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9068. # self.plots_updated.emit()
  9069. def disable_plots(self, objects):
  9070. """
  9071. Disables plots
  9072. :param objects: list of Objects to be disabled
  9073. :return:
  9074. """
  9075. # if no objects selected then do nothing
  9076. if not self.collection.get_selected():
  9077. return
  9078. log.debug("Disabling plots ...")
  9079. # self.inform.emit(_("Working ..."))
  9080. for obj in objects:
  9081. if obj.options['plot'] is True:
  9082. obj.options.set_change_callback(lambda x: None)
  9083. obj.options['plot'] = False
  9084. obj.options.set_change_callback(obj.on_options_change)
  9085. try:
  9086. self.delete_selection_shape()
  9087. except Exception as e:
  9088. log.debug("App.disable_plots() --> %s" % str(e))
  9089. # self.plots_updated.emit()
  9090. def worker_task(objects):
  9091. with self.proc_container.new(_("Disabling plots ...")):
  9092. for obj in objects:
  9093. # obj.options['plot'] = True
  9094. if isinstance(obj, FlatCAMCNCjob):
  9095. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9096. else:
  9097. obj.plot(visible=False)
  9098. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9099. def toggle_plots(self, objects):
  9100. """
  9101. Toggle plots visibility
  9102. :param objects: list of Objects for which to be toggled the visibility
  9103. :return:
  9104. """
  9105. # if no objects selected then do nothing
  9106. if not self.collection.get_selected():
  9107. return
  9108. log.debug("Toggling plots ...")
  9109. self.inform.emit(_("Working ..."))
  9110. for obj in objects:
  9111. if obj.options['plot'] is False:
  9112. obj.options['plot'] = True
  9113. else:
  9114. obj.options['plot'] = False
  9115. self.plots_updated.emit()
  9116. def clear_plots(self):
  9117. objects = self.collection.get_list()
  9118. for obj in objects:
  9119. obj.clear(obj == objects[-1])
  9120. # Clear pool to free memory
  9121. self.clear_pool()
  9122. def generate_cnc_job(self, objects):
  9123. self.report_usage("generate_cnc_job()")
  9124. # for obj in objects:
  9125. # obj.generatecncjob()
  9126. for obj in objects:
  9127. obj.on_generatecnc_button_click()
  9128. def save_project(self, filename, quit_action=False):
  9129. """
  9130. Saves the current project to the specified file.
  9131. :param filename: Name of the file in which to save.
  9132. :type filename: str
  9133. :param quit_action: if the project saving will be followed by an app quit; boolean
  9134. :return: None
  9135. """
  9136. self.log.debug("save_project()")
  9137. self.save_in_progress = True
  9138. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  9139. # Capture the latest changes
  9140. # Current object
  9141. try:
  9142. self.collection.get_active().read_form()
  9143. except:
  9144. self.log.debug("There was no active object")
  9145. pass
  9146. # Project options
  9147. self.options_read_form()
  9148. # Serialize the whole project
  9149. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9150. "options": self.options,
  9151. "version": self.version}
  9152. if self.defaults["global_save_compressed"] is True:
  9153. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9154. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9155. # # Write
  9156. f.write(g)
  9157. self.inform.emit('[success] %s: %s' %
  9158. (_("Project saved to"), filename))
  9159. else:
  9160. # Open file
  9161. try:
  9162. f = open(filename, 'w')
  9163. except IOError:
  9164. App.log.error("Failed to open file for saving: %s", filename)
  9165. return
  9166. # Write
  9167. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9168. f.close()
  9169. # verification of the saved project
  9170. # Open and parse
  9171. try:
  9172. saved_f = open(filename, 'r')
  9173. except IOError:
  9174. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9175. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9176. )
  9177. return
  9178. try:
  9179. saved_d = json.load(saved_f, object_hook=dict2obj)
  9180. except:
  9181. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9182. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9183. )
  9184. f.close()
  9185. return
  9186. saved_f.close()
  9187. if 'version' in saved_d:
  9188. self.inform.emit('[success] %s: %s' %
  9189. (_("Project saved to"), filename))
  9190. else:
  9191. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9192. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9193. )
  9194. settings = QSettings("Open Source", "FlatCAM")
  9195. lock_state = self.ui.lock_action.isChecked()
  9196. settings.setValue('toolbar_lock', lock_state)
  9197. # This will write the setting to the platform specific storage.
  9198. del settings
  9199. # if quit:
  9200. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9201. # t.start()
  9202. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9203. def start_delayed_quit(self, delay, filename, should_quit=None):
  9204. """
  9205. :param delay: period of checking if project file size is more than zero; in seconds
  9206. :param filename: the name of the project file to be checked periodically for size more than zero
  9207. :param should_quit: if the task finished will be followed by an app quit; boolean
  9208. :return:
  9209. """
  9210. to_quit = should_quit
  9211. self.save_timer = QtCore.QTimer()
  9212. self.save_timer.setInterval(delay)
  9213. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9214. self.save_timer.start()
  9215. def check_project_file_size(self, filename, should_quit=None):
  9216. """
  9217. :param filename: the name of the project file to be checked periodically for size more than zero
  9218. :param should_quit: will quit the app if True; boolean
  9219. :return:
  9220. """
  9221. try:
  9222. if os.stat(filename).st_size > 0:
  9223. self.save_in_progress = False
  9224. self.save_timer.stop()
  9225. if should_quit:
  9226. self.app_quit.emit()
  9227. except Exception as e:
  9228. traceback.print_exc()
  9229. def on_options_app2project(self):
  9230. """
  9231. Callback for Options->Transfer Options->App=>Project. Copies options
  9232. from application defaults to project defaults.
  9233. :return: None
  9234. """
  9235. self.report_usage("on_options_app2project")
  9236. self.defaults_read_form()
  9237. self.options.update(self.defaults)
  9238. self.options_write_form()
  9239. def on_options_project2app(self):
  9240. """
  9241. Callback for Options->Transfer Options->Project=>App. Copies options
  9242. from project defaults to application defaults.
  9243. :return: None
  9244. """
  9245. self.report_usage("on_options_project2app")
  9246. self.options_read_form()
  9247. self.defaults.update(self.options)
  9248. self.defaults_write_form()
  9249. def on_options_project2object(self):
  9250. """
  9251. Callback for Options->Transfer Options->Project=>Object. Copies options
  9252. from project defaults to the currently selected object.
  9253. :return: None
  9254. """
  9255. self.report_usage("on_options_project2object")
  9256. self.options_read_form()
  9257. obj = self.collection.get_active()
  9258. if obj is None:
  9259. self.inform.emit('[WARNING_NOTCL] %s' %
  9260. _("No object selected."))
  9261. return
  9262. for option in self.options:
  9263. if option.find(obj.kind + "_") == 0:
  9264. oname = option[len(obj.kind) + 1:]
  9265. obj.options[oname] = self.options[option]
  9266. obj.to_form() # Update UI
  9267. def on_options_object2project(self):
  9268. """
  9269. Callback for Options->Transfer Options->Object=>Project. Copies options
  9270. from the currently selected object to project defaults.
  9271. :return: None
  9272. """
  9273. self.report_usage("on_options_object2project")
  9274. obj = self.collection.get_active()
  9275. if obj is None:
  9276. self.inform.emit('[WARNING_NOTCL] %s' %
  9277. _("No object selected."))
  9278. return
  9279. obj.read_form()
  9280. for option in obj.options:
  9281. if option in ['name']: # TODO: Handle this better...
  9282. continue
  9283. self.options[obj.kind + "_" + option] = obj.options[option]
  9284. self.options_write_form()
  9285. def on_options_object2app(self):
  9286. """
  9287. Callback for Options->Transfer Options->Object=>App. Copies options
  9288. from the currently selected object to application defaults.
  9289. :return: None
  9290. """
  9291. self.report_usage("on_options_object2app")
  9292. obj = self.collection.get_active()
  9293. if obj is None:
  9294. self.inform.emit('[WARNING_NOTCL] %s' %
  9295. _("No object selected."))
  9296. return
  9297. obj.read_form()
  9298. for option in obj.options:
  9299. if option in ['name']: # TODO: Handle this better...
  9300. continue
  9301. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9302. self.defaults_write_form()
  9303. def on_options_app2object(self):
  9304. """
  9305. Callback for Options->Transfer Options->App=>Object. Copies options
  9306. from application defaults to the currently selected object.
  9307. :return: None
  9308. """
  9309. self.report_usage("on_options_app2object")
  9310. self.defaults_read_form()
  9311. obj = self.collection.get_active()
  9312. if obj is None:
  9313. self.inform.emit('[WARNING_NOTCL] %s' %
  9314. _("No object selected."))
  9315. return
  9316. for option in self.defaults:
  9317. if option.find(obj.kind + "_") == 0:
  9318. oname = option[len(obj.kind) + 1:]
  9319. obj.options[oname] = self.defaults[option]
  9320. obj.to_form() # Update UI
  9321. class ArgsThread(QtCore.QObject):
  9322. open_signal = pyqtSignal(list)
  9323. start = pyqtSignal()
  9324. if sys.platform == 'win32':
  9325. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9326. else:
  9327. address = ('/tmp/testipc', 'AF_UNIX')
  9328. def __init__(self):
  9329. super(ArgsThread, self).__init__()
  9330. self.start.connect(self.run)
  9331. def my_loop(self, address):
  9332. try:
  9333. listener = Listener(*address)
  9334. while True:
  9335. conn = listener.accept()
  9336. self.serve(conn)
  9337. except socket.error as e:
  9338. conn = Client(*address)
  9339. conn.send(sys.argv)
  9340. conn.send('close')
  9341. # close the current instance only if there are args
  9342. if len(sys.argv) > 1:
  9343. sys.exit()
  9344. def serve(self, conn):
  9345. while True:
  9346. msg = conn.recv()
  9347. if msg == 'close':
  9348. break
  9349. self.open_signal.emit(msg)
  9350. conn.close()
  9351. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9352. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9353. @pyqtSlot()
  9354. def run(self):
  9355. self.my_loop(self.address)
  9356. class GracefulException(Exception):
  9357. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9358. def __init__(self):
  9359. super().__init__()
  9360. def __str__(self):
  9361. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9362. # end of file