FlatCAMApp.py 362 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242
  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, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. import threading
  14. from stat import S_IREAD, S_IRGRP, S_IROTH
  15. import subprocess
  16. import tkinter as tk
  17. from PyQt5 import QtPrintSupport
  18. import urllib.request, urllib.parse, urllib.error
  19. from contextlib import contextmanager
  20. import gc
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. ########################################
  23. ## Imports part of FlatCAM ##
  24. ########################################
  25. from ObjectCollection import *
  26. from FlatCAMObj import *
  27. from flatcamGUI.PlotCanvas import *
  28. from flatcamGUI.FlatCAMGUI import *
  29. from FlatCAMCommon import LoudDict
  30. from FlatCAMPostProc import load_postprocessors
  31. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  32. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  33. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  34. from FlatCAMProcess import *
  35. from FlatCAMWorkerStack import WorkerStack
  36. from flatcamGUI.VisPyVisuals import Color
  37. from vispy.gloo.util import _screenshot
  38. from vispy.io import write_png
  39. from flatcamTools import *
  40. from multiprocessing import Pool
  41. import tclCommands
  42. import gettext
  43. import FlatCAMTranslation as fcTranslate
  44. fcTranslate.apply_language('strings')
  45. import builtins
  46. if '_' not in builtins.__dict__:
  47. _ = gettext.gettext
  48. ########################################
  49. ## App ##
  50. ########################################
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = 8.915
  80. version_date = "2019/05/11"
  81. beta = True
  82. # current date now
  83. date = str(datetime.today()).rpartition('.')[0]
  84. date = ''.join(c for c in date if c not in ':-')
  85. date = date.replace(' ', '_')
  86. # URL for update checks and statistics
  87. version_url = "http://flatcam.org/version"
  88. # App URL
  89. app_url = "http://flatcam.org"
  90. # Manual URL
  91. manual_url = "http://flatcam.org/manual/index.html"
  92. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  93. # this variable will hold the project status
  94. # if True it will mean that the project was modified and not saved
  95. should_we_save = False
  96. # flag is True if saving action has been triggered
  97. save_in_progress = False
  98. ##################
  99. ## Signals ##
  100. ##################
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. app_quit = QtCore.pyqtSignal()
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. self.main_thread = QtWidgets.QApplication.instance().thread()
  149. ###################
  150. ### OS-specific ###
  151. ###################
  152. # Folder for user settings.
  153. if sys.platform == 'win32':
  154. from win32com.shell import shell, shellcon
  155. if platform.architecture()[0] == '32bit':
  156. App.log.debug("Win32!")
  157. else:
  158. App.log.debug("Win64!")
  159. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  163. self.os = 'unix'
  164. ###############################
  165. ### Setup folders and files ###
  166. ###############################
  167. if not os.path.exists(self.data_path):
  168. os.makedirs(self.data_path)
  169. App.log.debug('Created data folder: ' + self.data_path)
  170. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  171. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  172. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  173. if not os.path.exists(self.postprocessorpaths):
  174. os.makedirs(self.postprocessorpaths)
  175. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  176. # create current_defaults.FlatConfig file if there is none
  177. try:
  178. f = open(self.data_path + '/current_defaults.FlatConfig')
  179. f.close()
  180. except IOError:
  181. App.log.debug('Creating empty current_defaults.FlatConfig')
  182. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  183. json.dump({}, f)
  184. f.close()
  185. # create factory_defaults.FlatConfig file if there is none
  186. try:
  187. f = open(self.data_path + '/factory_defaults.FlatConfig')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty factory_defaults.FlatConfig')
  191. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  192. json.dump({}, f)
  193. f.close()
  194. try:
  195. f = open(self.data_path + '/recent.json')
  196. f.close()
  197. except IOError:
  198. App.log.debug('Creating empty recent.json')
  199. f = open(self.data_path + '/recent.json', 'w')
  200. json.dump([], f)
  201. f.close()
  202. # Application directory. CHDIR to it. Otherwise, trying to load
  203. # GUI icons will fail as their path is relative.
  204. # This will fail under cx_freeze ...
  205. self.app_home = os.path.dirname(os.path.realpath(__file__))
  206. App.log.debug("Application path is " + self.app_home)
  207. App.log.debug("Started in " + os.getcwd())
  208. # cx_freeze workaround
  209. if os.path.isfile(self.app_home):
  210. self.app_home = os.path.dirname(self.app_home)
  211. os.chdir(self.app_home)
  212. # Create multiprocessing pool
  213. self.pool = Pool()
  214. # variable to store mouse coordinates
  215. self.mouse = [0, 0]
  216. ####################
  217. ## Initialize GUI ##
  218. ####################
  219. # FlatCAM colors used in plotting
  220. self.FC_light_green = '#BBF268BF'
  221. self.FC_dark_green = '#006E20BF'
  222. self.FC_light_blue = '#a5a5ffbf'
  223. self.FC_dark_blue = '#0000ffbf'
  224. QtCore.QObject.__init__(self)
  225. self.ui = FlatCAMGUI(self.version, self.beta, self)
  226. # self.connect(self.ui,
  227. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  228. # self.save_geometry) PyQt4
  229. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  230. self.ui.final_save.connect(self.final_save)
  231. ##############
  232. #### Data ####
  233. ##############
  234. self.recent = []
  235. self.clipboard = QtWidgets.QApplication.clipboard()
  236. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  237. self.project_filename = None
  238. self.toggle_units_ignore = False
  239. # self.defaults_form = PreferencesUI()
  240. # when adding entries here read the comments in the method found bellow named:
  241. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  242. self.defaults_form_fields = {
  243. # General App
  244. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  245. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  246. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  247. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  248. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  249. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  250. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  251. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  252. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  253. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  254. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  255. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  256. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  257. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  258. # General GUI Preferences
  259. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  260. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  261. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  262. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  263. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  264. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  265. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  266. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  267. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  268. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  269. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  270. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  271. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  272. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  273. # General GUI Settings
  274. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  275. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  276. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  277. # Gerber General
  278. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  279. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  280. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  281. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  282. # Gerber Options
  283. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  284. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  285. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  286. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  287. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  288. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  289. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  290. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  291. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  292. # Gerber Advanced Options
  293. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  294. "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  295. "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  296. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  297. # Excellon General
  298. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  299. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  300. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  301. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  302. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  303. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  304. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  305. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  306. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  307. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  308. # Excellon Options
  309. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  310. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  311. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  312. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  313. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  314. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  315. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  316. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  317. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  318. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  319. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  320. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  321. # Excellon Advanced Options
  322. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  323. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  324. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  325. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  326. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  327. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  328. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  329. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  330. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  331. # Excellon Export
  332. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  333. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  334. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  335. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  336. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  337. # Geometry General
  338. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  339. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  340. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  341. # Geometry Options
  342. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  343. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  344. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  345. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  346. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  347. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  348. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  349. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  350. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  351. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  352. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  353. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  354. # Geometry Advanced Options
  355. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  356. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  357. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  358. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  359. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  360. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  361. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  362. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  363. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  364. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  365. # CNCJob General
  366. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  367. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  368. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  369. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  370. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  371. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  372. # CNC Job Options
  373. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  374. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  375. # CNC Job Advanced Options
  376. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  377. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  378. # NCC Tool
  379. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  380. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  381. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  382. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  383. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  384. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  385. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  386. # CutOut Tool
  387. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  388. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  389. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  390. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  391. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  392. # Paint Area Tool
  393. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  394. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  395. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  396. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  397. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  398. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  399. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  400. # 2-sided Tool
  401. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  402. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  403. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  404. # Film Tool
  405. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  406. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  407. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  408. # Panelize Tool
  409. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  410. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  411. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  412. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  413. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  414. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  415. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  416. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  417. # Calculators Tool
  418. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  419. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  420. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  421. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  422. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  423. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  424. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  425. # Transformations Tool
  426. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  427. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  428. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  429. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  430. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  431. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  432. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  433. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  434. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  435. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  436. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  437. # SolderPaste Dispensing Tool
  438. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  439. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  440. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  441. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  442. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  443. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  444. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  445. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  446. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  447. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  448. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  449. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  450. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  451. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  452. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  453. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  454. }
  455. #############################
  456. #### LOAD POSTPROCESSORS ####
  457. #############################
  458. self.postprocessors = load_postprocessors(self)
  459. for name in list(self.postprocessors.keys()):
  460. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  461. if name.partition('_')[0] == 'Paste':
  462. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  463. continue
  464. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  465. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  466. if name == 'hpgl':
  467. continue
  468. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  469. #############################
  470. #### LOAD LANGUAGES ####
  471. #############################
  472. self.languages = fcTranslate.load_languages()
  473. for name in sorted(self.languages.values()):
  474. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  475. self.defaults = LoudDict()
  476. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  477. self.defaults.update({
  478. # Global APP Preferences
  479. "global_serial": 0,
  480. "global_stats": {},
  481. "units": "IN",
  482. "global_app_level": 'b',
  483. "global_language": 'English',
  484. "global_version_check": True,
  485. "global_send_stats": True,
  486. "global_pan_button": '2',
  487. "global_mselect_key": 'Control',
  488. "global_project_at_startup": False,
  489. "global_project_autohide": True,
  490. "global_toggle_tooltips": True,
  491. "global_worker_number": 2,
  492. "global_compression_level": 3,
  493. "global_save_compressed": True,
  494. # Global GUI Preferences
  495. "global_gridx": 0.0393701,
  496. "global_gridy": 0.0393701,
  497. "global_snap_max": 0.001968504,
  498. "global_workspace": False,
  499. "global_workspaceT": "A4P",
  500. "global_grid_context_menu": {
  501. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  502. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  503. },
  504. "global_plot_fill": '#BBF268BF',
  505. "global_plot_line": '#006E20BF',
  506. "global_sel_fill": '#a5a5ffbf',
  507. "global_sel_line": '#0000ffbf',
  508. "global_alt_sel_fill": '#BBF268BF',
  509. "global_alt_sel_line": '#006E20BF',
  510. "global_draw_color": '#FF0000',
  511. "global_sel_draw_color": '#0000FF',
  512. "global_proj_item_color": '#000000',
  513. "global_toolbar_view": 511,
  514. "global_background_timeout": 300000, # Default value is 5 minutes
  515. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  516. # (python trace only for unknown errors),
  517. # 1 = show trace(show trace allways),
  518. # 2 = (For the future).
  519. # Persistence
  520. "global_last_folder": None,
  521. "global_last_save_folder": None,
  522. # Default window geometry
  523. "global_def_win_x": 100,
  524. "global_def_win_y": 100,
  525. "global_def_win_w": 1024,
  526. "global_def_win_h": 650,
  527. "global_def_notebook_width": 1,
  528. # Constants...
  529. "global_defaults_save_period_ms": 20000, # Time between default saves.
  530. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  531. "global_shell_at_startup": False, # Show the shell at startup.
  532. "global_recent_limit": 10, # Max. items in recent list.
  533. "fit_key": 'V',
  534. "zoom_out_key": '-',
  535. "zoom_in_key": '=',
  536. "grid_toggle_key": 'G',
  537. "zoom_ratio": 1.5,
  538. "global_point_clipboard_format": "(%.4f, %.4f)",
  539. "global_zdownrate": None,
  540. # General GUI Settings
  541. "global_hover": True,
  542. "global_selection_shape": True,
  543. "global_layout": "compact",
  544. # Gerber General
  545. "gerber_plot": True,
  546. "gerber_solid": True,
  547. "gerber_multicolored": False,
  548. "gerber_isotooldia": 0.016,
  549. "gerber_isopasses": 1,
  550. "gerber_isooverlap": 0.15,
  551. # Gerber Options
  552. "gerber_combine_passes": False,
  553. "gerber_milling_type": "cl",
  554. "gerber_noncoppermargin": 0.1,
  555. "gerber_noncopperrounded": False,
  556. "gerber_bboxmargin": 0.1,
  557. "gerber_bboxrounded": False,
  558. "gerber_circle_steps": 64,
  559. "gerber_use_buffer_for_union": True,
  560. # Gerber Advanced Options
  561. "gerber_aperture_display": False,
  562. "gerber_aperture_scale_factor": 1.0,
  563. "gerber_aperture_buffer_factor": 0.0,
  564. "gerber_follow": False,
  565. # Excellon General
  566. "excellon_plot": True,
  567. "excellon_solid": True,
  568. "excellon_format_upper_in": 2,
  569. "excellon_format_lower_in": 4,
  570. "excellon_format_upper_mm": 3,
  571. "excellon_format_lower_mm": 3,
  572. "excellon_zeros": "L",
  573. "excellon_units": "INCH",
  574. "excellon_optimization_type": 'B',
  575. "excellon_search_time": 3,
  576. # Excellon Options
  577. "excellon_drillz": -0.1,
  578. "excellon_travelz": 0.1,
  579. "excellon_feedrate": 3.0,
  580. "excellon_spindlespeed": None,
  581. "excellon_dwell": False,
  582. "excellon_dwelltime": 1,
  583. "excellon_toolchange": False,
  584. "excellon_toolchangez": 1.0,
  585. "excellon_ppname_e": 'default',
  586. "excellon_tooldia": 0.016,
  587. "excellon_slot_tooldia": 0.016,
  588. "excellon_gcode_type": "drills",
  589. # Excellon Advanced Options
  590. "excellon_offset": 0.0,
  591. "excellon_toolchangexy": "0.0, 0.0",
  592. "excellon_startz": None,
  593. "excellon_endz": 2.0,
  594. "excellon_feedrate_rapid": 3.0,
  595. "excellon_z_pdepth": -0.02,
  596. "excellon_feedrate_probe": 3.0,
  597. "excellon_f_plunge": False,
  598. "excellon_f_retract": False,
  599. # Excellon Export
  600. "excellon_exp_units": 'INCH',
  601. "excellon_exp_format": 'ndec',
  602. "excellon_exp_integer": 2,
  603. "excellon_exp_decimals": 4,
  604. "excellon_exp_zeros": 'LZ',
  605. # Geometry General
  606. "geometry_plot": True,
  607. "geometry_circle_steps": 64,
  608. "geometry_cnctooldia": 0.016,
  609. # Geometry Options
  610. "geometry_cutz": -0.002,
  611. "geometry_multidepth": False,
  612. "geometry_depthperpass": 0.002,
  613. "geometry_travelz": 0.1,
  614. "geometry_toolchange": False,
  615. "geometry_toolchangez": 1.0,
  616. "geometry_feedrate": 3.0,
  617. "geometry_feedrate_z": 3.0,
  618. "geometry_spindlespeed": None,
  619. "geometry_dwell": False,
  620. "geometry_dwelltime": 1,
  621. "geometry_ppname_g": 'default',
  622. # Geometry Advanced Options
  623. "geometry_toolchangexy": "0.0, 0.0",
  624. "geometry_startz": None,
  625. "geometry_endz": 2.0,
  626. "geometry_feedrate_rapid": 3.0,
  627. "geometry_extracut": False,
  628. "geometry_z_pdepth": -0.02,
  629. "geometry_f_plunge": False,
  630. "geometry_feedrate_probe": 3.0,
  631. "geometry_segx": 0.0,
  632. "geometry_segy": 0.0,
  633. # CNC Job General
  634. "cncjob_plot": True,
  635. "cncjob_plot_kind": 'all',
  636. "cncjob_tooldia": 0.0393701,
  637. "cncjob_coords_decimals": 4,
  638. "cncjob_fr_decimals": 2,
  639. "cncjob_steps_per_circle": 64,
  640. # CNC Job Options
  641. "cncjob_prepend": "",
  642. "cncjob_append": "",
  643. # CNC Job Advanced Options
  644. "cncjob_toolchange_macro": "",
  645. "cncjob_toolchange_macro_enable": False,
  646. "tools_ncctools": "0.0393701, 0.019685",
  647. "tools_nccoverlap": 0.015748,
  648. "tools_nccmargin": 0.00393701,
  649. "tools_nccmethod": "seed",
  650. "tools_nccconnect": True,
  651. "tools_ncccontour": True,
  652. "tools_nccrest": False,
  653. "tools_cutouttooldia": 0.00393701,
  654. "tools_cutoutmargin": 0.00393701,
  655. "tools_cutoutgapsize": 0.005905512,
  656. "tools_gaps_ff": "8",
  657. "tools_cutout_convexshape": False,
  658. "tools_painttooldia": 0.07,
  659. "tools_paintoverlap": 0.15,
  660. "tools_paintmargin": 0.0,
  661. "tools_paintmethod": "seed",
  662. "tools_selectmethod": "single",
  663. "tools_pathconnect": True,
  664. "tools_paintcontour": True,
  665. "tools_2sided_mirror_axis": "X",
  666. "tools_2sided_axis_loc": "point",
  667. "tools_2sided_drilldia": 0.0393701,
  668. "tools_film_type": 'neg',
  669. "tools_film_boundary": 0.0393701,
  670. "tools_film_scale": 0,
  671. "tools_panelize_spacing_columns": 0,
  672. "tools_panelize_spacing_rows": 0,
  673. "tools_panelize_columns": 1,
  674. "tools_panelize_rows": 1,
  675. "tools_panelize_constrain": False,
  676. "tools_panelize_constrainx": 0.0,
  677. "tools_panelize_constrainy": 0.0,
  678. "tools_panelize_panel_type": 'gerber',
  679. "tools_calc_vshape_tip_dia": 0.007874,
  680. "tools_calc_vshape_tip_angle": 30,
  681. "tools_calc_vshape_cut_z": 0.000787,
  682. "tools_calc_electro_length": 10.0,
  683. "tools_calc_electro_width": 10.0,
  684. "tools_calc_electro_cdensity":13.0,
  685. "tools_calc_electro_growth": 10.0,
  686. "tools_transform_rotate": 90,
  687. "tools_transform_skew_x": 0.0,
  688. "tools_transform_skew_y": 0.0,
  689. "tools_transform_scale_x": 1.0,
  690. "tools_transform_scale_y": 1.0,
  691. "tools_transform_scale_link": True,
  692. "tools_transform_scale_reference": True,
  693. "tools_transform_offset_x": 0.0,
  694. "tools_transform_offset_y": 0.0,
  695. "tools_transform_mirror_reference": False,
  696. "tools_transform_mirror_point": (0, 0),
  697. "tools_solderpaste_tools": "0.0393701, 0.011811",
  698. "tools_solderpaste_new": 0.011811,
  699. "tools_solderpaste_z_start": 0.00019685039,
  700. "tools_solderpaste_z_dispense": 0.00393701,
  701. "tools_solderpaste_z_stop": 0.00019685039,
  702. "tools_solderpaste_z_travel": 0.00393701,
  703. "tools_solderpaste_z_toolchange": 0.0393701,
  704. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  705. "tools_solderpaste_frxy": 3.0,
  706. "tools_solderpaste_frz": 3.0,
  707. "tools_solderpaste_frz_dispense": 0.0393701,
  708. "tools_solderpaste_speedfwd": 20,
  709. "tools_solderpaste_dwellfwd": 1,
  710. "tools_solderpaste_speedrev": 10,
  711. "tools_solderpaste_dwellrev": 1,
  712. "tools_solderpaste_pp": 'Paste_1'
  713. })
  714. ###############################
  715. ### Load defaults from file ###
  716. ###############################
  717. if user_defaults:
  718. self.load_defaults(filename='current_defaults')
  719. ############################
  720. ##### APPLY APP LANGUAGE ###
  721. ############################
  722. ret_val = fcTranslate.apply_language('strings')
  723. if ret_val == "no language":
  724. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  725. log.debug("Could not find the Language files. The App strings are missing.")
  726. else:
  727. # make the current language the current selection on the language combobox
  728. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  729. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  730. ###################################
  731. ### CREATE UNIQUE SERIAL NUMBER ###
  732. ###################################
  733. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  734. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  735. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  736. self.save_defaults(silent=True)
  737. self.propagate_defaults(silent=True)
  738. self.restore_main_win_geom()
  739. def auto_save_defaults():
  740. try:
  741. self.save_defaults(silent=True)
  742. self.propagate_defaults(silent=True)
  743. finally:
  744. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  745. # the following lines activates automatic defaults save
  746. # if user_defaults:
  747. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  748. # self.options_form = PreferencesUI()
  749. self.options_form_fields = {
  750. "units": self.ui.general_options_form.general_app_group.units_radio,
  751. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  752. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  753. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  754. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  755. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  756. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  757. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  758. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  759. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  760. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  761. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  762. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  763. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  764. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  765. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  766. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  767. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  768. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  769. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  770. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  771. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  772. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  773. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  774. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  775. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  776. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  777. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  778. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  779. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  780. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  781. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  782. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  783. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  784. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  785. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  786. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  787. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  788. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  789. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  790. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  791. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  792. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  793. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  794. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  795. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  796. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  797. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  798. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  799. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  800. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  801. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  802. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  803. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  804. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  805. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  806. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  807. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  808. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  809. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  810. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  811. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  812. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  813. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  814. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  815. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  816. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  817. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  818. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  819. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  820. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  821. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  822. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  823. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  824. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  825. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  826. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  827. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  828. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  829. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  830. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  831. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  832. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  833. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  834. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  835. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  836. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  837. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  838. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  839. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  840. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  841. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  842. }
  843. for name in list(self.postprocessors.keys()):
  844. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  845. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  846. self.options = LoudDict()
  847. self.options.set_change_callback(self.on_options_dict_change)
  848. self.options.update({
  849. "units": "IN",
  850. "global_gridx": 1.0,
  851. "global_gridy": 1.0,
  852. "global_snap_max": 0.05,
  853. "global_background_timeout": 300000, # Default value is 5 minutes
  854. "global_verbose_error_level": 0, # Shell verbosity:
  855. # 0 = default(python trace only for unknown errors),
  856. # 1 = show trace(show trace allways), 2 = (For the future).
  857. "gerber_plot": True,
  858. "gerber_solid": True,
  859. "gerber_multicolored": False,
  860. "gerber_isotooldia": 0.016,
  861. "gerber_isopasses": 1,
  862. "gerber_isooverlap": 0.15,
  863. "gerber_combine_passes": True,
  864. "gerber_noncoppermargin": 0.0,
  865. "gerber_noncopperrounded": False,
  866. "gerber_bboxmargin": 0.0,
  867. "gerber_bboxrounded": False,
  868. "excellon_plot": True,
  869. "excellon_solid": False,
  870. "excellon_format_upper_in": 2,
  871. "excellon_format_lower_in": 4,
  872. "excellon_format_upper_mm": 3,
  873. "excellon_format_lower_mm": 3,
  874. "excellon_units": 'INCH',
  875. "excellon_optimization_type": 'B',
  876. "excellon_search_time": 3,
  877. "excellon_zeros": "L",
  878. "excellon_drillz": -0.1,
  879. "excellon_travelz": 0.1,
  880. "excellon_feedrate": 3.0,
  881. "excellon_feedrate_rapid": 3.0,
  882. "excellon_spindlespeed": None,
  883. "excellon_dwell": True,
  884. "excellon_dwelltime": 1000,
  885. "excellon_toolchange": False,
  886. "excellon_toolchangez": 1.0,
  887. "excellon_toolchangexy": "0.0, 0.0",
  888. "excellon_tooldia": 0.016,
  889. "excellon_ppname_e": 'default',
  890. "excellon_f_plunge": False,
  891. "excellon_startz": None,
  892. "excellon_endz": 2.0,
  893. "geometry_plot": True,
  894. "geometry_segx": 0.0,
  895. "geometry_segy": 0.0,
  896. "geometry_cutz": -0.002,
  897. "geometry_travelz": 0.1,
  898. "geometry_feedrate": 3.0,
  899. "geometry_feedrate_z": 3.0,
  900. "geometry_feedrate_rapid": 3.0,
  901. "geometry_spindlespeed": None,
  902. "geometry_dwell": True,
  903. "geometry_dwelltime": 1000,
  904. "geometry_cnctooldia": 0.016,
  905. "geometry_toolchange": False,
  906. "geometry_toolchangez": 2.0,
  907. "geometry_toolchangexy": "0.0, 0.0",
  908. "geometry_startz": None,
  909. "geometry_endz": 2.0,
  910. "geometry_ppname_g": "default",
  911. "geometry_f_plunge": False,
  912. "geometry_depthperpass": 0.002,
  913. "geometry_multidepth": False,
  914. "geometry_extracut": False,
  915. "cncjob_plot": True,
  916. "cncjob_tooldia": 0.016,
  917. "cncjob_prepend": "",
  918. "cncjob_append": "",
  919. "tools_ncctools": "1.0, 0.5",
  920. "tools_nccoverlap": 0.4,
  921. "tools_nccmargin": 1,
  922. "tools_cutouttooldia": 0.07,
  923. "tools_cutoutmargin": 0.1,
  924. "tools_cutoutgapsize": 0.15,
  925. "tools_gaps_ff": "8",
  926. "tools_painttooldia": 0.07,
  927. "tools_paintoverlap": 0.15,
  928. "tools_paintmargin": 0.0,
  929. "tools_paintmethod": "seed",
  930. "tools_selectmethod": "single",
  931. "tools_pathconnect": True,
  932. "tools_paintcontour": True,
  933. "tools_2sided_mirror_axis": "X",
  934. "tools_2sided_axis_loc": 'point',
  935. "tools_2sided_drilldia": 1,
  936. "tools_film_type": 'neg',
  937. "tools_film_boundary": 1,
  938. "tools_film_scale": 0,
  939. "tools_panelize_spacing_columns": 0,
  940. "tools_panelize_spacing_rows": 0,
  941. "tools_panelize_columns": 1,
  942. "tools_panelize_rows": 1,
  943. "tools_panelize_constrain": False,
  944. "tools_panelize_constrainx": 0.0,
  945. "tools_panelize_constrainy": 0.0
  946. })
  947. self.options.update(self.defaults) # Copy app defaults to project options
  948. self.gen_form = None
  949. self.ger_form = None
  950. self.exc_form = None
  951. self.geo_form = None
  952. self.cnc_form = None
  953. self.tools_form = None
  954. self.on_options_combo_change(0) # Will show the initial form
  955. ### Define OBJECT COLLECTION ###
  956. self.collection = ObjectCollection(self)
  957. self.ui.project_tab_layout.addWidget(self.collection.view)
  958. ###
  959. self.log.debug("Finished creating Object Collection.")
  960. ### Initialize the color box's color in Preferences -> Global -> Color
  961. # Init Plot Colors
  962. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  963. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  964. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  965. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  966. int(self.defaults['global_plot_fill'][7:9], 16))
  967. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  968. int(self.defaults['global_plot_fill'][7:9], 16))
  969. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  970. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  971. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  972. # Init Left-Right Selection colors
  973. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  974. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  975. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  976. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  977. int(self.defaults['global_sel_fill'][7:9], 16))
  978. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  979. int(self.defaults['global_sel_fill'][7:9], 16))
  980. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  981. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  982. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  983. # Init Right-Left Selection colors
  984. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  985. self.defaults['global_alt_sel_fill'])
  986. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  987. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  988. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  989. int(self.defaults['global_sel_fill'][7:9], 16))
  990. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  991. int(self.defaults['global_sel_fill'][7:9], 16))
  992. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  993. self.defaults['global_alt_sel_line'])
  994. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  995. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  996. # Init Draw color and Selection Draw Color
  997. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  998. self.defaults['global_draw_color'])
  999. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1000. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1001. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1002. self.defaults['global_sel_draw_color'])
  1003. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1004. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1005. # Init Project Items color
  1006. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1007. self.defaults['global_proj_item_color'])
  1008. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1009. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1010. #### End of Data ####
  1011. #### Plot Area ####
  1012. start_plot_time = time.time() # debug
  1013. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  1014. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  1015. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  1016. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  1017. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  1018. # Keys over plot enabled
  1019. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  1020. self.ui.splitter.setStretchFactor(1, 2)
  1021. # So it can receive key presses
  1022. self.plotcanvas.vispy_canvas.native.setFocus()
  1023. self.app_cursor = self.plotcanvas.new_cursor()
  1024. self.app_cursor.enabled = False
  1025. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1026. # depending on from where those tools are called different actions can be done
  1027. self.call_source = 'app'
  1028. end_plot_time = time.time()
  1029. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1030. ### EDITOR section
  1031. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1032. self.exc_editor = FlatCAMExcEditor(self)
  1033. self.grb_editor = FlatCAMGrbEditor(self)
  1034. #### Adjust tabs width ####
  1035. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1036. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1037. self.collection.view.setMinimumWidth(290)
  1038. self.log.debug("Finished adding FlatCAM Editor's.")
  1039. #### Worker ####
  1040. if self.defaults["global_worker_number"]:
  1041. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1042. else:
  1043. self.workers = WorkerStack(workers_number=2)
  1044. self.worker_task.connect(self.workers.add_task)
  1045. ### Signal handling ###
  1046. ## Custom signals
  1047. self.inform.connect(self.info)
  1048. self.app_quit.connect(self.quit_application)
  1049. self.message.connect(self.message_dialog)
  1050. self.progress.connect(self.set_progress_bar)
  1051. self.object_created.connect(self.on_object_created)
  1052. self.object_changed.connect(self.on_object_changed)
  1053. self.object_plotted.connect(self.on_object_plotted)
  1054. self.plots_updated.connect(self.on_plots_updated)
  1055. self.file_opened.connect(self.register_recent)
  1056. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1057. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1058. ## Standard signals
  1059. # Menu
  1060. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1061. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1062. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1063. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1064. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1065. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1066. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1067. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1068. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1069. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1070. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1071. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1072. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1073. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1074. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1075. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1076. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1077. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1078. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1079. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1080. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1081. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1082. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1083. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1084. self.ui.menufile_exit.triggered.connect(self.final_save)
  1085. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1086. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1087. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1088. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1089. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1090. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1091. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1092. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1093. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1094. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  1095. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1096. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1097. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1098. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1099. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1100. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1101. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1102. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1103. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1104. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1105. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1106. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1107. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1108. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1109. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1110. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1111. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1112. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1113. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1114. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1115. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1116. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1117. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1118. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1119. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1120. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1121. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1122. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1123. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1124. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1125. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1126. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1127. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1128. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1129. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1130. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1131. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1132. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1133. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1134. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1135. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1136. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1137. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1138. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1139. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1140. # ToolBar signals
  1141. self.connect_toolbar_signals()
  1142. # Context Menu
  1143. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1144. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1145. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1146. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1147. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1148. self.ui.clearplot.triggered.connect(self.clear_plots)
  1149. self.ui.replot.triggered.connect(self.plot_all)
  1150. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1151. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1152. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1153. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1154. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1155. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1156. # Preferences Plot Area TAB
  1157. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1158. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1159. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1160. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1161. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1162. ###############################
  1163. ### GUI PREFERENCES SIGNALS ###
  1164. ###############################
  1165. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1166. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1167. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1168. )
  1169. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(self.on_toggle_units)
  1170. ###############################
  1171. ### GUI PREFERENCES SIGNALS ###
  1172. ###############################
  1173. # Setting plot colors signals
  1174. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1175. self.on_pf_color_entry)
  1176. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1177. self.on_pf_color_button)
  1178. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1179. self.on_pf_color_spinner)
  1180. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1181. self.on_pf_color_slider)
  1182. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1183. self.on_pl_color_entry)
  1184. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1185. self.on_pl_color_button)
  1186. # Setting selection (left - right) colors signals
  1187. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1188. self.on_sf_color_entry)
  1189. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1190. self.on_sf_color_button)
  1191. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1192. self.on_sf_color_spinner)
  1193. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1194. self.on_sf_color_slider)
  1195. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1196. self.on_sl_color_entry)
  1197. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1198. self.on_sl_color_button)
  1199. # Setting selection (right - left) colors signals
  1200. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1201. self.on_alt_sf_color_entry)
  1202. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1203. self.on_alt_sf_color_button)
  1204. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1205. self.on_alt_sf_color_spinner)
  1206. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1207. self.on_alt_sf_color_slider)
  1208. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1209. self.on_alt_sl_color_entry)
  1210. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1211. self.on_alt_sl_color_button)
  1212. # Setting Editor Draw colors signals
  1213. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1214. self.on_draw_color_entry)
  1215. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1216. self.on_draw_color_button)
  1217. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1218. self.on_sel_draw_color_entry)
  1219. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1220. self.on_sel_draw_color_button)
  1221. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1222. self.on_proj_color_entry)
  1223. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1224. self.on_proj_color_button)
  1225. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1226. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1227. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1228. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1229. self.on_cnc_custom_parameters)
  1230. # Modify G-CODE Plot Area TAB
  1231. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1232. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1233. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1234. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1235. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1236. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1237. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1238. # Object list
  1239. self.collection.view.activated.connect(self.on_row_activated)
  1240. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1241. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1242. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1243. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1244. self.on_excellon_defaults_button)
  1245. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1246. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1247. self.on_excellon_options_button)
  1248. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1249. self.tool_tab_locked = False
  1250. # decide if to show or hide the Notebook side of the screen at startup
  1251. if self.defaults["global_project_at_startup"] is True:
  1252. self.ui.splitter.setSizes([1, 1])
  1253. else:
  1254. self.ui.splitter.setSizes([0, 1])
  1255. ####################
  1256. ### Other setups ###
  1257. ####################
  1258. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1259. self.setup_obj_classes()
  1260. self.setup_recent_items()
  1261. self.setup_component_editor()
  1262. #############
  1263. ### Shell ###
  1264. #############
  1265. ###
  1266. # Auto-complete KEYWORDS
  1267. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1268. 'aligndrill', 'clear',
  1269. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1270. 'export_gcode',
  1271. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1272. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1273. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1274. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1275. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1276. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1277. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1278. ]
  1279. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1280. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1281. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1282. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1283. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1284. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1285. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1286. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1287. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1288. ]
  1289. self.tcl_keywords = [
  1290. "after", "append", "apply", "array", "auto_execok", "auto_import", "auto_load", "auto_mkindex",
  1291. "auto_qualify", "auto_reset", "bgerror", "binary", "break", "case", "catch", "cd", "chan", "clock", "close",
  1292. "concat", "continue", "coroutine", "dict", "encoding", "eof", "error", "eval", "exec", "exit", "expr",
  1293. "fblocked", "fconfigure", "fcopy", "file", "fileevent", "flush", "for", "foreach", "format", "gets", "glob",
  1294. "global", "history", "if", "incr", "info", "interp", "join", "lappend", "lassign", "lindex", "linsert",
  1295. "list", "llength", "load", "lrange", "lrepeat", "lreplace", "lreverse", "lsearch", "lset", "lsort",
  1296. "mathfunc", "mathop", "memory", "my", "namespace", "next", "nextto", "open", "package", "parray", "pid",
  1297. "pkg_mkIndex", "platform", "proc", "puts", "pwd", "read", "refchan", "regexp", "regsub", "rename", "return",
  1298. "scan", "seek", "self", "set", "socket", "source", "split", "string", "subst", "switch", "tailcall",
  1299. "tcl_endOfWord", "tcl_findLibrary", "tcl_startOfNextWord", "tcl_startOfPreviousWord", "tcl_wordBreakAfter",
  1300. "tcl_wordBreakBefore", "tell", "throw", "time", "tm", "trace", "transchan", "try", "unknown", "unload",
  1301. "unset", "update", "uplevel", "upvar", "variable", "vwait", "while", "yield", "yieldto", "zlib",
  1302. "attemptckalloc", "attemptckrealloc", "ckalloc", "ckfree", "ckrealloc", "Tcl_Access", "Tcl_AddErrorInfo",
  1303. "Tcl_AddObjErrorInfo", "Tcl_AlertNotifier", "Tcl_Alloc", "Tcl_AllocStatBuf", "Tcl_AllowExceptions",
  1304. "Tcl_AppendAllObjTypes", "Tcl_AppendElement", "Tcl_AppendExportList", "Tcl_AppendFormatToObj",
  1305. "Tcl_AppendLimitedToObj", "Tcl_AppendObjToErrorInfo", "Tcl_AppendObjToObj", "Tcl_AppendPrintfToObj",
  1306. "Tcl_AppendResult", "Tcl_AppendResultVA", "Tcl_AppendStringsToObj", "Tcl_AppendStringsToObjVA",
  1307. "Tcl_AppendToObj", "Tcl_AppendUnicodeToObj", "Tcl_AppInit", "Tcl_AsyncCreate", "Tcl_AsyncDelete",
  1308. "Tcl_AsyncInvoke", "Tcl_AsyncMark", "Tcl_AsyncReady", "Tcl_AttemptAlloc", "Tcl_AttemptRealloc",
  1309. "Tcl_AttemptSetObjLength", "Tcl_BackgroundError", "Tcl_BackgroundException", "Tcl_Backslash",
  1310. "Tcl_BadChannelOption", "Tcl_CallWhenDeleted", "Tcl_Canceled", "Tcl_CancelEval", "Tcl_CancelIdleCall",
  1311. "Tcl_ChannelBlockModeProc", "Tcl_ChannelBuffered", "Tcl_ChannelClose2Proc", "Tcl_ChannelCloseProc",
  1312. "Tcl_ChannelFlushProc", "Tcl_ChannelGetHandleProc", "Tcl_ChannelGetOptionProc", "Tcl_ChannelHandlerProc",
  1313. "Tcl_ChannelInputProc", "Tcl_ChannelName", "Tcl_ChannelOutputProc", "Tcl_ChannelSeekProc",
  1314. "Tcl_ChannelSetOptionProc", "Tcl_ChannelThreadActionProc", "Tcl_ChannelTruncateProc", "Tcl_ChannelVersion",
  1315. "Tcl_ChannelWatchProc", "Tcl_ChannelWideSeekProc", "Tcl_Chdir", "Tcl_ClassGetMetadata",
  1316. "Tcl_ClassSetConstructor", "Tcl_ClassSetDestructor", "Tcl_ClassSetMetadata", "Tcl_ClearChannelHandlers",
  1317. "Tcl_Close", "Tcl_CommandComplete", "Tcl_CommandTraceInfo", "Tcl_Concat", "Tcl_ConcatObj",
  1318. "Tcl_ConditionFinalize", "Tcl_ConditionNotify", "Tcl_ConditionWait", "Tcl_ConvertCountedElement",
  1319. "Tcl_ConvertElement", "Tcl_ConvertToType", "Tcl_CopyObjectInstance", "Tcl_CreateAlias",
  1320. "Tcl_CreateAliasObj", "Tcl_CreateChannel", "Tcl_CreateChannelHandler", "Tcl_CreateCloseHandler",
  1321. "Tcl_CreateCommand", "Tcl_CreateEncoding", "Tcl_CreateEnsemble", "Tcl_CreateEventSource",
  1322. "Tcl_CreateExitHandler", "Tcl_CreateFileHandler", "Tcl_CreateHashEntry", "Tcl_CreateInterp",
  1323. "Tcl_CreateMathFunc", "Tcl_CreateNamespace", "Tcl_CreateObjCommand", "Tcl_CreateObjTrace",
  1324. "Tcl_CreateSlave", "Tcl_CreateThread", "Tcl_CreateThreadExitHandler", "Tcl_CreateTimerHandler",
  1325. "Tcl_CreateTrace", "Tcl_CutChannel", "Tcl_DecrRefCount", "Tcl_DeleteAssocData", "Tcl_DeleteChannelHandler",
  1326. "Tcl_DeleteCloseHandler", "Tcl_DeleteCommand", "Tcl_DeleteCommandFromToken", "Tcl_DeleteEvents",
  1327. "Tcl_DeleteEventSource", "Tcl_DeleteExitHandler", "Tcl_DeleteFileHandler", "Tcl_DeleteHashEntry",
  1328. "Tcl_DeleteHashTable", "Tcl_DeleteInterp", "Tcl_DeleteNamespace", "Tcl_DeleteThreadExitHandler",
  1329. "Tcl_DeleteTimerHandler", "Tcl_DeleteTrace", "Tcl_DetachChannel", "Tcl_DetachPids", "Tcl_DictObjDone",
  1330. "Tcl_DictObjFirst", "Tcl_DictObjGet", "Tcl_DictObjNext", "Tcl_DictObjPut", "Tcl_DictObjPutKeyList",
  1331. "Tcl_DictObjRemove", "Tcl_DictObjRemoveKeyList", "Tcl_DictObjSize", "Tcl_DiscardInterpState",
  1332. "Tcl_DiscardResult", "Tcl_DontCallWhenDeleted", "Tcl_DoOneEvent", "Tcl_DoWhenIdle", "Tcl_DStringAppend",
  1333. "Tcl_DStringAppendElement", "Tcl_DStringEndSublist", "Tcl_DStringFree", "Tcl_DStringGetResult",
  1334. "Tcl_DStringInit", "Tcl_DStringLength", "Tcl_DStringResult", "Tcl_DStringSetLength",
  1335. "Tcl_DStringStartSublist", "Tcl_DStringTrunc", "Tcl_DStringValue", "Tcl_DumpActiveMemory",
  1336. "Tcl_DuplicateObj", "Tcl_Eof", "Tcl_ErrnoId", "Tcl_ErrnoMsg", "Tcl_Eval", "Tcl_EvalEx", "Tcl_EvalFile",
  1337. "Tcl_EvalObjEx", "Tcl_EvalObjv", "Tcl_EvalTokens", "Tcl_EvalTokensStandard", "Tcl_EventuallyFree",
  1338. "Tcl_Exit", "Tcl_ExitThread", "Tcl_Export", "Tcl_ExposeCommand", "Tcl_ExprBoolean", "Tcl_ExprBooleanObj",
  1339. "Tcl_ExprDouble", "Tcl_ExprDoubleObj", "Tcl_ExprLong", "Tcl_ExprLongObj", "Tcl_ExprObj", "Tcl_ExprString",
  1340. "Tcl_ExternalToUtf", "Tcl_ExternalToUtfDString", "Tcl_Finalize", "Tcl_FinalizeNotifier",
  1341. "Tcl_FinalizeThread", "Tcl_FindCommand", "Tcl_FindEnsemble", "Tcl_FindExecutable", "Tcl_FindHashEntry",
  1342. "Tcl_FindNamespace", "Tcl_FirstHashEntry", "Tcl_Flush", "Tcl_ForgetImport", "Tcl_Format",
  1343. "Tcl_Free· Tcl_FreeEncoding", "Tcl_FreeParse", "Tcl_FreeResult", "Tcl_FSAccess", "Tcl_FSChdir",
  1344. "Tcl_FSConvertToPathType", "Tcl_FSCopyDirectory", "Tcl_FSCopyFile", "Tcl_FSCreateDirectory", "Tcl_FSData",
  1345. "Tcl_FSDeleteFile", "Tcl_FSEqualPaths", "Tcl_FSEvalFile", "Tcl_FSEvalFileEx", "Tcl_FSFileAttrsGet",
  1346. "Tcl_FSFileAttrsSet", "Tcl_FSFileAttrStrings", "Tcl_FSFileSystemInfo", "Tcl_FSGetCwd",
  1347. "Tcl_FSGetFileSystemForPath", "Tcl_FSGetInternalRep", "Tcl_FSGetNativePath", "Tcl_FSGetNormalizedPath",
  1348. "Tcl_FSGetPathType", "Tcl_FSGetTranslatedPath", "Tcl_FSGetTranslatedStringPath", "Tcl_FSJoinPath",
  1349. "Tcl_FSJoinToPath", "Tcl_FSLink· Tcl_FSListVolumes", "Tcl_FSLoadFile", "Tcl_FSLstat",
  1350. "Tcl_FSMatchInDirectory", "Tcl_FSMountsChanged", "Tcl_FSNewNativePath", "Tcl_FSOpenFileChannel",
  1351. "Tcl_FSPathSeparator", "Tcl_FSRegister", "Tcl_FSRemoveDirectory", "Tcl_FSRenameFile", "Tcl_FSSplitPath",
  1352. "Tcl_FSStat", "Tcl_FSUnloadFile", "Tcl_FSUnregister", "Tcl_FSUtime", "Tcl_GetAccessTimeFromStat",
  1353. "Tcl_GetAlias", "Tcl_GetAliasObj", "Tcl_GetAssocData", "Tcl_GetBignumFromObj", "Tcl_GetBlocksFromStat",
  1354. "Tcl_GetBlockSizeFromStat", "Tcl_GetBoolean", "Tcl_GetBooleanFromObj", "Tcl_GetByteArrayFromObj",
  1355. "Tcl_GetChangeTimeFromStat", "Tcl_GetChannel", "Tcl_GetChannelBufferSize", "Tcl_GetChannelError",
  1356. "Tcl_GetChannelErrorInterp", "Tcl_GetChannelHandle", "Tcl_GetChannelInstanceData", "Tcl_GetChannelMode",
  1357. "Tcl_GetChannelName", "Tcl_GetChannelNames", "Tcl_GetChannelNamesEx", "Tcl_GetChannelOption",
  1358. "Tcl_GetChannelThread", "Tcl_GetChannelType", "Tcl_GetCharLength", "Tcl_GetClassAsObject",
  1359. "Tcl_GetCommandFromObj", "Tcl_GetCommandFullName", "Tcl_GetCommandInfo", "Tcl_GetCommandInfoFromToken",
  1360. "Tcl_GetCommandName", "Tcl_GetCurrentNamespace", "Tcl_GetCurrentThread", "Tcl_GetCwd",
  1361. "Tcl_GetDefaultEncodingDir", "Tcl_GetDeviceTypeFromStat", "Tcl_GetDouble", "Tcl_GetDoubleFromObj",
  1362. "Tcl_GetEncoding", "Tcl_GetEncodingFromObj", "Tcl_GetEncodingName", "Tcl_GetEncodingNameFromEnvironment",
  1363. "Tcl_GetEncodingNames", "Tcl_GetEncodingSearchPath", "Tcl_GetEnsembleFlags", "Tcl_GetEnsembleMappingDict",
  1364. "Tcl_GetEnsembleNamespace", "Tcl_GetEnsembleParameterList", "Tcl_GetEnsembleSubcommandList",
  1365. "Tcl_GetEnsembleUnknownHandler", "Tcl_GetErrno", "Tcl_GetErrorLine", "Tcl_GetFSDeviceFromStat",
  1366. "Tcl_GetFSInodeFromStat", "Tcl_GetGlobalNamespace", "Tcl_GetGroupIdFromStat", "Tcl_GetHashKey",
  1367. "Tcl_GetHashValue", "Tcl_GetHostName", "Tcl_GetIndexFromObj", "Tcl_GetIndexFromObjStruct", "Tcl_GetInt",
  1368. "Tcl_GetInterpPath", "Tcl_GetIntFromObj", "Tcl_GetLinkCountFromStat", "Tcl_GetLongFromObj", "Tcl_GetMaster",
  1369. "Tcl_GetMathFuncInfo", "Tcl_GetModeFromStat", "Tcl_GetModificationTimeFromStat", "Tcl_GetNameOfExecutable",
  1370. "Tcl_GetNamespaceUnknownHandler", "Tcl_GetObjectAsClass", "Tcl_GetObjectCommand", "Tcl_GetObjectFromObj",
  1371. "Tcl_GetObjectName", "Tcl_GetObjectNamespace", "Tcl_GetObjResult", "Tcl_GetObjType", "Tcl_GetOpenFile",
  1372. "Tcl_GetPathType", "Tcl_GetRange", "Tcl_GetRegExpFromObj", "Tcl_GetReturnOptions", "Tcl_Gets",
  1373. "Tcl_GetServiceMode", "Tcl_GetSizeFromStat", "Tcl_GetSlave", "Tcl_GetsObj", "Tcl_GetStackedChannel",
  1374. "Tcl_GetStartupScript", "Tcl_GetStdChannel", "Tcl_GetString", "Tcl_GetStringFromObj", "Tcl_GetStringResult",
  1375. "Tcl_GetThreadData", "Tcl_GetTime", "Tcl_GetTopChannel", "Tcl_GetUniChar", "Tcl_GetUnicode",
  1376. "Tcl_GetUnicodeFromObj", "Tcl_GetUserIdFromStat", "Tcl_GetVar", "Tcl_GetVar2", "Tcl_GetVar2Ex",
  1377. "Tcl_GetVersion", "Tcl_GetWideIntFromObj", "Tcl_GlobalEval", "Tcl_GlobalEvalObj", "Tcl_HashStats",
  1378. "Tcl_HideCommand", "Tcl_Import", "Tcl_IncrRefCount", "Tcl_Init", "Tcl_InitCustomHashTable",
  1379. "Tcl_InitHashTable", "Tcl_InitMemory", "Tcl_InitNotifier", "Tcl_InitObjHashTable", "Tcl_InitStubs",
  1380. "Tcl_InputBlocked", "Tcl_InputBuffered", "Tcl_InterpActive", "Tcl_InterpDeleted", "Tcl_InvalidateStringRep",
  1381. "Tcl_IsChannelExisting", "Tcl_IsChannelRegistered", "Tcl_IsChannelShared", "Tcl_IsEnsemble", "Tcl_IsSafe",
  1382. "Tcl_IsShared", "Tcl_IsStandardChannel", "Tcl_JoinPath", "Tcl_JoinThread", "Tcl_LimitAddHandler",
  1383. "Tcl_LimitCheck", "Tcl_LimitExceeded", "Tcl_LimitGetCommands", "Tcl_LimitGetGranularity",
  1384. "Tcl_LimitGetTime", "Tcl_LimitReady", "Tcl_LimitRemoveHandler", "Tcl_LimitSetCommands",
  1385. "Tcl_LimitSetGranularity", "Tcl_LimitSetTime", "Tcl_LimitTypeEnabled", "Tcl_LimitTypeExceeded",
  1386. "Tcl_LimitTypeReset", "Tcl_LimitTypeSet", "Tcl_LinkVar", "Tcl_ListMathFuncs", "Tcl_ListObjAppendElement",
  1387. "Tcl_ListObjAppendList", "Tcl_ListObjGetElements", "Tcl_ListObjIndex", "Tcl_ListObjLength",
  1388. "Tcl_ListObjReplace", "Tcl_LogCommandInfo", "Tcl_Main", "Tcl_MakeFileChannel", "Tcl_MakeSafe",
  1389. "Tcl_MakeTcpClientChannel", "Tcl_Merge", "Tcl_MethodDeclarerClass", "Tcl_MethodDeclarerObject",
  1390. "Tcl_MethodIsPublic", "Tcl_MethodIsType", "Tcl_MethodName", "Tcl_MutexFinalize", "Tcl_MutexLock",
  1391. "Tcl_MutexUnlock", "Tcl_NewBignumObj", "Tcl_NewBooleanObj", "Tcl_NewByteArrayObj", "Tcl_NewDictObj",
  1392. "Tcl_NewDoubleObj", "Tcl_NewInstanceMethod", "Tcl_NewIntObj", "Tcl_NewListObj", "Tcl_NewLongObj",
  1393. "Tcl_NewMethod", "Tcl_NewObj", "Tcl_NewObjectInstance", "Tcl_NewStringObj", "Tcl_NewUnicodeObj",
  1394. "Tcl_NewWideIntObj", "Tcl_NextHashEntry", "Tcl_NotifyChannel", "Tcl_NRAddCallback", "Tcl_NRCallObjProc",
  1395. "Tcl_NRCmdSwap", "Tcl_NRCreateCommand", "Tcl_NREvalObj", "Tcl_NREvalObjv", "Tcl_NumUtfChars",
  1396. "Tcl_ObjectContextInvokeNext", "Tcl_ObjectContextIsFiltering", "Tcl_ObjectContextMethod",
  1397. "Tcl_ObjectContextObject", "Tcl_ObjectContextSkippedArgs", "Tcl_ObjectDeleted", "Tcl_ObjectGetMetadata",
  1398. "Tcl_ObjectGetMethodNameMapper", "Tcl_ObjectSetMetadata", "Tcl_ObjectSetMethodNameMapper", "Tcl_ObjGetVar2",
  1399. "Tcl_ObjPrintf", "Tcl_ObjSetVar2", "Tcl_OpenCommandChannel", "Tcl_OpenFileChannel", "Tcl_OpenTcpClient",
  1400. "Tcl_OpenTcpServer", "Tcl_OutputBuffered", "Tcl_Panic", "Tcl_PanicVA", "Tcl_ParseArgsObjv",
  1401. "Tcl_ParseBraces", "Tcl_ParseCommand", "Tcl_ParseExpr", "Tcl_ParseQuotedString", "Tcl_ParseVar",
  1402. "Tcl_ParseVarName", "Tcl_PkgPresent", "Tcl_PkgPresentEx", "Tcl_PkgProvide", "Tcl_PkgProvideEx",
  1403. "Tcl_PkgRequire", "Tcl_PkgRequireEx", "Tcl_PkgRequireProc", "Tcl_PosixError", "Tcl_Preserve",
  1404. "Tcl_PrintDouble", "Tcl_PutEnv", "Tcl_QueryTimeProc", "Tcl_QueueEvent", "Tcl_Read", "Tcl_ReadChars",
  1405. "Tcl_ReadRaw", "Tcl_Realloc", "Tcl_ReapDetachedProcs", "Tcl_RecordAndEval", "Tcl_RecordAndEvalObj",
  1406. "Tcl_RegExpCompile", "Tcl_RegExpExec", "Tcl_RegExpExecObj", "Tcl_RegExpGetInfo", "Tcl_RegExpMatch",
  1407. "Tcl_RegExpMatchObj", "Tcl_RegExpRange", "Tcl_RegisterChannel", "Tcl_RegisterConfig", "Tcl_RegisterObjType",
  1408. "Tcl_Release", "Tcl_ResetResult", "Tcl_RestoreInterpState", "Tcl_RestoreResult", "Tcl_SaveInterpState",
  1409. "Tcl_SaveResult", "Tcl_ScanCountedElement", "Tcl_ScanElement", "Tcl_Seek", "Tcl_ServiceAll",
  1410. "Tcl_ServiceEvent", "Tcl_ServiceModeHook", "Tcl_SetAssocData", "Tcl_SetBignumObj", "Tcl_SetBooleanObj",
  1411. "Tcl_SetByteArrayLength", "Tcl_SetByteArrayObj", "Tcl_SetChannelBufferSize", "Tcl_SetChannelError",
  1412. "Tcl_SetChannelErrorInterp", "Tcl_SetChannelOption", "Tcl_SetCommandInfo", "Tcl_SetCommandInfoFromToken",
  1413. "Tcl_SetDefaultEncodingDir", "Tcl_SetDoubleObj", "Tcl_SetEncodingSearchPath", "Tcl_SetEnsembleFlags",
  1414. "Tcl_SetEnsembleMappingDict", "Tcl_SetEnsembleParameterList", "Tcl_SetEnsembleSubcommandList",
  1415. "Tcl_SetEnsembleUnknownHandler", "Tcl_SetErrno", "Tcl_SetErrorCode", "Tcl_SetErrorCodeVA",
  1416. "Tcl_SetErrorLine", "Tcl_SetExitProc", "Tcl_SetHashValue", "Tcl_SetIntObj", "Tcl_SetListObj",
  1417. "Tcl_SetLongObj", "Tcl_SetMainLoop", "Tcl_SetMaxBlockTime", "Tcl_SetNamespaceUnknownHandler",
  1418. "Tcl_SetNotifier", "Tcl_SetObjErrorCode", "Tcl_SetObjLength", "Tcl_SetObjResult", "Tcl_SetPanicProc",
  1419. "Tcl_SetRecursionLimit", "Tcl_SetResult", "Tcl_SetReturnOptions", "Tcl_SetServiceMode",
  1420. "Tcl_SetStartupScript", "Tcl_SetStdChannel", "Tcl_SetStringObj", "Tcl_SetSystemEncoding", "Tcl_SetTimeProc",
  1421. "Tcl_SetTimer", "Tcl_SetUnicodeObj", "Tcl_SetVar", "Tcl_SetVar2", "Tcl_SetVar2Ex", "Tcl_SetWideIntObj",
  1422. "Tcl_SignalId", "Tcl_SignalMsg", "Tcl_Sleep", "Tcl_SourceRCFile", "Tcl_SpliceChannel", "Tcl_SplitList",
  1423. "Tcl_SplitPath", "Tcl_StackChannel", "Tcl_StandardChannels", "Tcl_Stat", "Tcl_StaticPackage",
  1424. "Tcl_StringCaseMatch", "Tcl_StringMatch", "Tcl_SubstObj", "Tcl_TakeBignumFromObj", "Tcl_Tell",
  1425. "Tcl_ThreadAlert", "Tcl_ThreadQueueEvent", "Tcl_TraceCommand", "Tcl_TraceVar", "Tcl_TraceVar2",
  1426. "Tcl_TransferResult", "Tcl_TranslateFileName", "Tcl_TruncateChannel", "Tcl_Ungets", "Tcl_UniChar",
  1427. "Tcl_UniCharAtIndex", "Tcl_UniCharCaseMatch", "Tcl_UniCharIsAlnum", "Tcl_UniCharIsAlpha",
  1428. "Tcl_UniCharIsControl", "Tcl_UniCharIsDigit", "Tcl_UniCharIsGraph", "Tcl_UniCharIsLower",
  1429. "Tcl_UniCharIsPrint", "Tcl_UniCharIsPunct", "Tcl_UniCharIsSpace", "Tcl_UniCharIsUpper",
  1430. "Tcl_UniCharIsWordChar", "Tcl_UniCharLen", "Tcl_UniCharNcasecmp", "Tcl_UniCharNcmp", "Tcl_UniCharToLower",
  1431. "Tcl_UniCharToTitle", "Tcl_UniCharToUpper", "Tcl_UniCharToUtf", "Tcl_UniCharToUtfDString", "Tcl_UnlinkVar",
  1432. "Tcl_UnregisterChannel", "Tcl_UnsetVar", "Tcl_UnsetVar2", "Tcl_UnstackChannel", "Tcl_UntraceCommand",
  1433. "Tcl_UntraceVar", "Tcl_UntraceVar2", "Tcl_UpdateLinkedVar", "Tcl_UpVar", "Tcl_UpVar2", "Tcl_UtfAtIndex",
  1434. "Tcl_UtfBackslash", "Tcl_UtfCharComplete", "Tcl_UtfFindFirst", "Tcl_UtfFindLast", "Tcl_UtfNext",
  1435. "Tcl_UtfPrev", "Tcl_UtfToExternal", "Tcl_UtfToExternalDString", "Tcl_UtfToLower", "Tcl_UtfToTitle",
  1436. "Tcl_UtfToUniChar", "Tcl_UtfToUniCharDString", "Tcl_UtfToUpper", "Tcl_ValidateAllMemory", "Tcl_VarEval",
  1437. "Tcl_VarEvalVA", "Tcl_VarTraceInfo", "Tcl_VarTraceInfo2", "Tcl_WaitForEvent", "Tcl_WaitPid",
  1438. "Tcl_WinTCharToUtf", "Tcl_WinUtfToTChar", "Tcl_Write", "Tcl_WriteChars", "Tcl_WriteObj", "Tcl_WriteRaw",
  1439. "Tcl_WrongNumArgs", "Tcl_ZlibAdler32", "Tcl_ZlibCRC32", "Tcl_ZlibDeflate", "Tcl_ZlibInflate",
  1440. "Tcl_ZlibStreamChecksum", "Tcl_ZlibStreamClose", "Tcl_ZlibStreamEof", "Tcl_ZlibStreamGet",
  1441. "Tcl_ZlibStreamGetCommandName", "Tcl_ZlibStreamInit", "Tcl_ZlibStreamPut", "dde", "http", "msgcat",
  1442. "registry", "tcltest", "Tcl_AllocHashEntryProc", "Tcl_AppInitProc", "Tcl_ArgvInfo", "Tcl_AsyncProc",
  1443. "Tcl_ChannelProc", "Tcl_ChannelType", "Tcl_CloneProc", "Tcl_CloseProc", "Tcl_CmdDeleteProc", "Tcl_CmdInfo",
  1444. "Tcl_CmdObjTraceDeleteProc", "Tcl_CmdObjTraceProc", "Tcl_CmdProc", "Tcl_CmdTraceProc",
  1445. "Tcl_CommandTraceProc", "Tcl_CompareHashKeysProc", "Tcl_Config", "Tcl_DriverBlockModeProc",
  1446. "Tcl_DriverClose2Proc", "Tcl_DriverCloseProc", "Tcl_DriverFlushProc", "Tcl_DriverGetHandleProc",
  1447. "Tcl_DriverGetOptionProc", "Tcl_DriverHandlerProc", "Tcl_DriverInputProc", "Tcl_DriverOutputProc",
  1448. "Tcl_DriverSeekProc", "Tcl_DriverSetOptionProc", "Tcl_DriverThreadActionProc", "Tcl_DriverTruncateProc",
  1449. "Tcl_DriverWatchProc", "Tcl_DriverWideSeekProc", "Tcl_DupInternalRepProc", "Tcl_EncodingConvertProc",
  1450. "Tcl_EncodingFreeProc", "Tcl_EncodingType", "Tcl_Event", "Tcl_EventCheckProc", "Tcl_EventDeleteProc",
  1451. "Tcl_EventProc", "Tcl_EventSetupProc", "Tcl_ExitProc", "Tcl_FileProc", "Tcl_Filesystem",
  1452. "Tcl_FreeHashEntryProc", "Tcl_FreeInternalRepProc", "Tcl_FreeProc", "Tcl_FSAccessProc", "Tcl_FSChdirProc",
  1453. "Tcl_FSCopyDirectoryProc", "Tcl_FSCopyFileProc", "Tcl_FSCreateDirectoryProc", "Tcl_FSCreateInternalRepProc",
  1454. "Tcl_FSDeleteFileProc", "Tcl_FSDupInternalRepProc", "Tcl_FSFileAttrsGetProc", "Tcl_FSFileAttrsSetProc",
  1455. "Tcl_FSFilesystemPathTypeProc", "Tcl_FSFilesystemSeparatorProc", "Tcl_FSFreeInternalRepProc",
  1456. "Tcl_FSGetCwdProc", "Tcl_FSInternalToNormalizedProc", "Tcl_FSLinkProc", "Tcl_FSListVolumesProc",
  1457. "Tcl_FSLoadFileProc", "Tcl_FSLstatProc", "Tcl_FSMatchInDirectoryProc", "Tcl_FSNormalizePathProc",
  1458. "Tcl_FSOpenFileChannelProc", "Tcl_FSPathInFilesystemProc", "Tcl_FSRemoveDirectoryProc",
  1459. "Tcl_FSRenameFileProc", "Tcl_FSStatProc", "Tcl_FSUnloadFileProc", "Tcl_FSUtimeProc", "Tcl_GlobTypeData",
  1460. "Tcl_HashKeyType", "Tcl_IdleProc", "Tcl_Interp", "Tcl_InterpDeleteProc", "Tcl_LimitHandlerDeleteProc",
  1461. "Tcl_LimitHandlerProc", "Tcl_MainLoopProc", "Tcl_MathProc", "Tcl_MethodCallProc", "Tcl_MethodDeleteProc",
  1462. "Tcl_MethodType", "Tcl_NamespaceDeleteProc", "Tcl_NotifierProcs", "Tcl_Obj", "Tcl_ObjCmdProc",
  1463. "Tcl_ObjectMapMethodNameProc", "Tcl_ObjectMetadataDeleteProc", "Tcl_ObjType", "Tcl_PackageInitProc",
  1464. "Tcl_PackageUnloadProc", "Tcl_PanicProc", "Tcl_RegExpIndices", "Tcl_RegExpInfo", "Tcl_ScaleTimeProc",
  1465. "Tcl_SetFromAnyProc", "Tcl_TcpAcceptProc", "Tcl_Time", "Tcl_TimerProc", "Tcl_Token", "Tcl_UpdateStringProc",
  1466. "Tcl_Value", "Tcl_VarTraceProc", "argc", "argv", "argv0", "auto_path", "env", "errorCode", "errorInfo",
  1467. "filename", "re_syntax", "safe", "Tcl", "tcl_interactive", "tcl_library", "TCL_MEM_DEBUG",
  1468. "tcl_nonwordchars", "tcl_patchLevel", "tcl_pkgPath", "tcl_platform", "tcl_precision", "tcl_rcFileName",
  1469. "tcl_traceCompile", "tcl_traceEval", "tcl_version", "tcl_wordchars"
  1470. ]
  1471. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1472. self.shell = FCShell(self, version=self.version)
  1473. self.shell._edit.set_model_data(self.myKeywords)
  1474. self.ui.code_editor.set_model_data(self.myKeywords)
  1475. self.shell.setWindowIcon(self.ui.app_icon)
  1476. self.shell.setWindowTitle("FlatCAM Shell")
  1477. self.shell.resize(*self.defaults["global_shell_shape"])
  1478. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1479. self.shell.append_output("(Type help to get started)\n\n")
  1480. self.init_tcl()
  1481. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1482. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1483. self.ui.shell_dock.setWidget(self.shell)
  1484. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1485. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1486. QtWidgets.QDockWidget.DockWidgetFloatable |
  1487. QtWidgets.QDockWidget.DockWidgetClosable)
  1488. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1489. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1490. if self.defaults["global_shell_at_startup"]:
  1491. self.ui.shell_dock.show()
  1492. else:
  1493. self.ui.shell_dock.hide()
  1494. #########################
  1495. ### Tools and Plugins ###
  1496. #########################
  1497. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1498. self.install_tools()
  1499. ### System Font Parsing ###
  1500. # self.f_parse = ParseFont(self)
  1501. # self.parse_system_fonts()
  1502. # test if the program was started with a script as parameter
  1503. if self.cmd_line_shellfile:
  1504. try:
  1505. with open(self.cmd_line_shellfile, "r") as myfile:
  1506. cmd_line_shellfile_text = myfile.read()
  1507. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1508. except Exception as ext:
  1509. print("ERROR: ", ext)
  1510. sys.exit(2)
  1511. ###########################
  1512. #### Check for updates ####
  1513. ###########################
  1514. # Separate thread (Not worker)
  1515. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1516. if (self.beta is False or self.beta is None) and \
  1517. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1518. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1519. self.thr2 = QtCore.QThread()
  1520. self.worker_task.emit({'fcn': self.version_check,
  1521. 'params': []})
  1522. self.thr2.start(QtCore.QThread.LowPriority)
  1523. ####################################
  1524. #### Variables for global usage ####
  1525. ####################################
  1526. # coordinates for relative position display
  1527. self.rel_point1 = (0, 0)
  1528. self.rel_point2 = (0, 0)
  1529. # variable to store coordinates
  1530. self.pos = (0, 0)
  1531. self.pos_jump = (0, 0)
  1532. # decide if we have a double click or single click
  1533. self.doubleclick = False
  1534. # variable to store if a command is active (then the var is not None) and which one it is
  1535. self.command_active = None
  1536. # variable to store the status of moving selection action
  1537. # None value means that it's not an selection action
  1538. # True value = a selection from left to right
  1539. # False value = a selection from right to left
  1540. self.selection_type = None
  1541. # List to store the objects that are currently loaded in FlatCAM
  1542. # This list is updated on each object creation or object delete
  1543. self.all_objects_list = []
  1544. # List to store the objects that are selected
  1545. self.sel_objects_list = []
  1546. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1547. self.key_modifiers = None
  1548. # Variable to hold the status of the axis
  1549. self.toggle_axis = True
  1550. # Variable to store the status of the fullscreen event
  1551. self.toggle_fscreen = False
  1552. # Variable to store the status of the code editor
  1553. self.toggle_codeeditor = False
  1554. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1555. self.click_noproject = False
  1556. self.cursor = None
  1557. # Variable to store the GCODE that was edited
  1558. self.gcode_edited = ""
  1559. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1560. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1561. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1562. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1563. ]
  1564. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1565. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1566. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1567. 'mpf']
  1568. self.svg_list = ['svg']
  1569. self.dxf_list = ['dxf']
  1570. self.pdf_list = ['pdf']
  1571. self.prj_list = ['flatprj']
  1572. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1573. # flag for polygons not cleared
  1574. self.poly_not_cleared = False
  1575. # VisPy visuals
  1576. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1577. self.isHovering = False
  1578. self.notHovering = True
  1579. ### Save defaults to factory_defaults.FlatConfig file ###
  1580. ### It's done only once after install #############
  1581. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1582. fac_def_from_file = factory_file.read()
  1583. factory_defaults = json.loads(fac_def_from_file)
  1584. # if the file contain an empty dictionary then save the factory defaults into the file
  1585. if not factory_defaults:
  1586. self.save_factory_defaults(silent=False)
  1587. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1588. initial_lay = 'compact'
  1589. self.on_layout(lay=initial_lay)
  1590. # Set the combobox in Preferences to the current layout
  1591. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  1592. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1593. factory_file.close()
  1594. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1595. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1596. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1597. # Post-GUI initialization: Experimental attempt
  1598. # to perform unit tests on the GUI.
  1599. # if post_gui is not None:
  1600. # post_gui(self)
  1601. App.log.debug("END of constructor. Releasing control.")
  1602. # accept a project file as command line parameter
  1603. # the path/file_name must be enclosed in quotes if it contain spaces
  1604. for argument in App.args:
  1605. if '.FlatPrj' in argument:
  1606. try:
  1607. project_name = str(argument)
  1608. if project_name == "":
  1609. self.inform.emit(_("Open cancelled."))
  1610. else:
  1611. # self.open_project(project_name)
  1612. run_from_arg = True
  1613. self.worker_task.emit({'fcn': self.open_project,
  1614. 'params': [project_name, run_from_arg]})
  1615. except Exception as e:
  1616. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1617. if '.FlatConfig' in argument:
  1618. try:
  1619. file_name = str(argument)
  1620. if file_name == "":
  1621. self.inform.emit(_("Open Config file failed."))
  1622. else:
  1623. # run_from_arg = True
  1624. # self.worker_task.emit({'fcn': self.open_config_file,
  1625. # 'params': [file_name, run_from_arg]})
  1626. self.open_config_file(file_name, run_from_arg=True)
  1627. except Exception as e:
  1628. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1629. if '.FlatScript' in argument:
  1630. try:
  1631. file_name = str(argument)
  1632. if file_name == "":
  1633. self.inform.emit(_("Open Script file failed."))
  1634. else:
  1635. # run_from_arg = True
  1636. # self.worker_task.emit({'fcn': self.open_script_file,
  1637. # 'params': [file_name, run_from_arg]})
  1638. self.on_filerunscript(name=file_name)
  1639. except Exception as e:
  1640. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1641. def defaults_read_form(self):
  1642. for option in self.defaults_form_fields:
  1643. try:
  1644. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1645. except:
  1646. pass
  1647. def defaults_write_form(self, factor=None):
  1648. for option in self.defaults:
  1649. self.defaults_write_form_field(option, factor=factor)
  1650. # try:
  1651. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1652. # except KeyError:
  1653. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1654. # # TODO: Rethink this?
  1655. # pass
  1656. def defaults_write_form_field(self, field, factor=None):
  1657. try:
  1658. if factor is None:
  1659. self.defaults_form_fields[field].set_value(self.defaults[field])
  1660. else:
  1661. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1662. except KeyError:
  1663. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1664. # TODO: Rethink this?
  1665. pass
  1666. except AttributeError:
  1667. log.debug(field)
  1668. def clear_pool(self):
  1669. self.pool.close()
  1670. self.pool = Pool()
  1671. self.pool_recreated.emit(self.pool)
  1672. gc.collect()
  1673. # the order that the tools are installed is important as they can depend on each other install position
  1674. def install_tools(self):
  1675. self.dblsidedtool = DblSidedTool(self)
  1676. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1677. self.measurement_tool = Measurement(self)
  1678. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1679. self.panelize_tool = Panelize(self)
  1680. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1681. self.film_tool = Film(self)
  1682. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1683. self.paste_tool = SolderPaste(self)
  1684. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  1685. self.calculator_tool = ToolCalculator(self)
  1686. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1687. self.sub_tool = ToolSub(self)
  1688. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menuedit_convert,
  1689. before=self.ui.menuedit_convert_sg2mg)
  1690. self.move_tool = ToolMove(self)
  1691. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1692. before=self.ui.menueditorigin)
  1693. self.cutout_tool = CutOut(self)
  1694. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1695. before=self.measurement_tool.menuAction)
  1696. self.ncclear_tool = NonCopperClear(self)
  1697. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1698. before=self.measurement_tool.menuAction, separator=True)
  1699. self.paint_tool = ToolPaint(self)
  1700. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1701. before=self.measurement_tool.menuAction, separator=True)
  1702. self.transform_tool = ToolTransform(self)
  1703. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1704. self.properties_tool = Properties(self)
  1705. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1706. self.pdf_tool = ToolPDF(self)
  1707. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  1708. separator=True)
  1709. self.image_tool = ToolImage(self)
  1710. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1711. separator=True)
  1712. self.pcb_wizard_tool = PcbWizard(self)
  1713. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  1714. self.log.debug("Tools are installed.")
  1715. def remove_tools(self):
  1716. for act in self.ui.menutool.actions():
  1717. self.ui.menutool.removeAction(act)
  1718. def init_tools(self):
  1719. log.debug("init_tools()")
  1720. # delete the data currently in the Tools Tab and the Tab itself
  1721. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1722. if widget is not None:
  1723. widget.deleteLater()
  1724. self.ui.notebook.removeTab(2)
  1725. # rebuild the Tools Tab
  1726. self.ui.tool_tab = QtWidgets.QWidget()
  1727. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1728. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1729. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1730. self.ui.tool_scroll_area = VerticalScrollArea()
  1731. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1732. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1733. # first remove all of them
  1734. self.remove_tools()
  1735. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1736. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1737. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1738. # third install all of them
  1739. self.install_tools()
  1740. self.log.debug("Tools are initialized.")
  1741. # def parse_system_fonts(self):
  1742. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1743. # 'params': []})
  1744. def connect_toolbar_signals(self):
  1745. # Toolbar
  1746. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1747. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1748. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1749. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1750. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1751. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1752. self.ui.replot_btn.triggered.connect(self.plot_all)
  1753. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1754. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1755. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1756. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1757. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1758. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1759. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1760. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1761. self.ui.delete_btn.triggered.connect(self.on_delete)
  1762. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1763. # Tools Toolbar Signals
  1764. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1765. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1766. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1767. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1768. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1769. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1770. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1771. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1772. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1773. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1774. def object2editor(self):
  1775. """
  1776. Send the current Geometry or Excellon object (if any) into the editor.
  1777. :return: None
  1778. """
  1779. self.report_usage("object2editor()")
  1780. edited_object = self.collection.get_active()
  1781. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  1782. isinstance(edited_object, FlatCAMExcellon):
  1783. pass
  1784. else:
  1785. self.inform.emit(_("[WARNING_NOTCL] Select a Geometry, Gerber or Excellon Object to edit."))
  1786. return
  1787. if isinstance(edited_object, FlatCAMGeometry):
  1788. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1789. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1790. if edited_object.multigeo is True:
  1791. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  1792. if len(edited_tools) > 1:
  1793. self.inform.emit(_("[WARNING_NOTCL] Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  1794. "is not possible.\n"
  1795. "Edit only one geometry at a time."))
  1796. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=edited_tools[0])
  1797. else:
  1798. self.geo_editor.edit_fcgeometry(edited_object)
  1799. # we set the notebook to hidden
  1800. self.ui.splitter.setSizes([0, 1])
  1801. # set call source to the Editor we go into
  1802. self.call_source = 'geo_editor'
  1803. elif isinstance(edited_object, FlatCAMExcellon):
  1804. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1805. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1806. self.exc_editor.edit_fcexcellon(edited_object)
  1807. # set call source to the Editor we go into
  1808. self.call_source = 'exc_editor'
  1809. elif isinstance(edited_object, FlatCAMGerber):
  1810. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1811. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1812. self.grb_editor.edit_fcgerber(edited_object)
  1813. # set call source to the Editor we go into
  1814. self.call_source = 'grb_editor'
  1815. # # make sure that we can't select another object while in Editor Mode:
  1816. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1817. self.ui.project_frame.setDisabled(True)
  1818. # delete any selection shape that might be active as they are not relevant in Editor
  1819. self.delete_selection_shape()
  1820. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1821. self.ui.plot_tab_area.protectTab(0)
  1822. self.inform.emit(_("[WARNING_NOTCL] Editor is activated ..."))
  1823. self.should_we_save = True
  1824. def editor2object(self, cleanup=None):
  1825. """
  1826. Transfers the Geometry or Excellon from the editor to the current object.
  1827. :return: None
  1828. """
  1829. self.report_usage("editor2object()")
  1830. # do not update a geometry or excellon object unless it comes out of an editor
  1831. if self.call_source != 'app':
  1832. edited_obj = self.collection.get_active()
  1833. obj_type = ""
  1834. if cleanup is None:
  1835. msgbox = QtWidgets.QMessageBox()
  1836. msgbox.setText(_("Do you want to save the edited object?"))
  1837. msgbox.setWindowTitle(_("Close Editor"))
  1838. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1839. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1840. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1841. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1842. msgbox.setDefaultButton(bt_yes)
  1843. msgbox.exec_()
  1844. response = msgbox.clickedButton()
  1845. if response == bt_yes:
  1846. if isinstance(edited_obj, FlatCAMGeometry):
  1847. obj_type = "Geometry"
  1848. if cleanup is None:
  1849. self.geo_editor.update_fcgeometry(edited_obj)
  1850. self.geo_editor.update_options(edited_obj)
  1851. self.geo_editor.deactivate()
  1852. # update the geo object options so it is including the bounding box values
  1853. try:
  1854. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1855. edited_obj.options['xmin'] = xmin
  1856. edited_obj.options['ymin'] = ymin
  1857. edited_obj.options['xmax'] = xmax
  1858. edited_obj.options['ymax'] = ymax
  1859. except AttributeError as e:
  1860. self.inform.emit(_("[WARNING] Object empty after edit."))
  1861. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1862. elif isinstance(edited_obj, FlatCAMGerber):
  1863. new_obj = self.collection.get_active()
  1864. obj_type = "Gerber"
  1865. if cleanup is None:
  1866. self.grb_editor.update_fcgerber(edited_obj)
  1867. self.grb_editor.update_options(new_obj)
  1868. self.grb_editor.deactivate_grb_editor()
  1869. # delete the old object (the source object) if it was an empty one
  1870. if edited_obj.solid_geometry.is_empty:
  1871. old_name = edited_obj.options['name']
  1872. self.collection.set_active(old_name)
  1873. self.collection.delete_active()
  1874. else:
  1875. # update the geo object options so it is including the bounding box values
  1876. # but don't do this for objects that are made out of empty source objects, it will fail
  1877. try:
  1878. xmin, ymin, xmax, ymax = new_obj.bounds()
  1879. new_obj.options['xmin'] = xmin
  1880. new_obj.options['ymin'] = ymin
  1881. new_obj.options['xmax'] = xmax
  1882. new_obj.options['ymax'] = ymax
  1883. except Exception as e:
  1884. self.inform.emit(_("[WARNING] Object empty after edit."))
  1885. log.debug("App.editor2object() --> Gerber --> %s" % str(e))
  1886. elif isinstance(edited_obj, FlatCAMExcellon):
  1887. obj_type = "Excellon"
  1888. if cleanup is None:
  1889. self.exc_editor.update_fcexcellon(edited_obj)
  1890. self.exc_editor.update_options(edited_obj)
  1891. self.exc_editor.deactivate()
  1892. else:
  1893. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1894. return
  1895. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1896. elif response == bt_no:
  1897. if isinstance(edited_obj, FlatCAMGeometry):
  1898. self.geo_editor.deactivate()
  1899. elif isinstance(edited_obj, FlatCAMGerber):
  1900. self.grb_editor.deactivate_grb_editor()
  1901. elif isinstance(edited_obj, FlatCAMExcellon):
  1902. self.exc_editor.deactivate()
  1903. # set focus on the project tab
  1904. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  1905. else:
  1906. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1907. return
  1908. elif response == bt_cancel:
  1909. return
  1910. else:
  1911. if isinstance(edited_obj, FlatCAMGeometry):
  1912. self.geo_editor.deactivate()
  1913. elif isinstance(edited_obj, FlatCAMGerber):
  1914. self.grb_editor.deactivate_grb_editor()
  1915. elif isinstance(edited_obj, FlatCAMExcellon):
  1916. self.exc_editor.deactivate()
  1917. else:
  1918. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1919. return
  1920. # if notebook is hidden we show it
  1921. if self.ui.splitter.sizes()[0] == 0:
  1922. self.ui.splitter.setSizes([1, 1])
  1923. # restore the call_source to app
  1924. self.call_source = 'app'
  1925. edited_obj.plot()
  1926. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1927. self.ui.plot_tab_area.protectTab(0)
  1928. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1929. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1930. self.ui.project_frame.setDisabled(False)
  1931. def get_last_folder(self):
  1932. return self.defaults["global_last_folder"]
  1933. def get_last_save_folder(self):
  1934. loc = self.defaults["global_last_save_folder"]
  1935. if loc is None:
  1936. loc = self.defaults["global_last_folder"]
  1937. if loc is None:
  1938. loc = os.path.dirname(__file__)
  1939. return loc
  1940. def report_usage(self, resource):
  1941. """
  1942. Increments usage counter for the given resource
  1943. in self.defaults['global_stats'].
  1944. :param resource: Name of the resource.
  1945. :return: None
  1946. """
  1947. if resource in self.defaults['global_stats']:
  1948. self.defaults['global_stats'][resource] += 1
  1949. else:
  1950. self.defaults['global_stats'][resource] = 1
  1951. def init_tcl(self):
  1952. if hasattr(self,'tcl'):
  1953. # self.tcl = None
  1954. # TODO we need to clean non default variables and procedures here
  1955. # new object cannot be used here as it will not remember values created for next passes,
  1956. # because tcl was execudted in old instance of TCL
  1957. pass
  1958. else:
  1959. self.tcl = tk.Tcl()
  1960. self.setup_shell()
  1961. self.log.debug("TCL Shell has been initialized.")
  1962. # TODO: This shouldn't be here.
  1963. class TclErrorException(Exception):
  1964. """
  1965. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1966. """
  1967. pass
  1968. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1969. """
  1970. Shows a message on the FlatCAM Shell
  1971. :param msg: Message to display.
  1972. :param show: Opens the shell.
  1973. :param error: Shows the message as an error.
  1974. :return: None
  1975. """
  1976. if show:
  1977. self.ui.shell_dock.show()
  1978. try:
  1979. if error:
  1980. self.shell.append_error(msg + "\n")
  1981. elif warning:
  1982. self.shell.append_warning(msg + "\n")
  1983. elif success:
  1984. self.shell.append_success(msg + "\n")
  1985. elif selected:
  1986. self.shell.append_selected(msg + "\n")
  1987. else:
  1988. self.shell.append_output(msg + "\n")
  1989. except AttributeError:
  1990. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1991. def raise_tcl_unknown_error(self, unknownException):
  1992. """
  1993. Raise exception if is different type than TclErrorException
  1994. this is here mainly to show unknown errors inside TCL shell console.
  1995. :param unknownException:
  1996. :return:
  1997. """
  1998. if not isinstance(unknownException, self.TclErrorException):
  1999. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2000. else:
  2001. raise unknownException
  2002. def display_tcl_error(self, error, error_info=None):
  2003. """
  2004. escape bracket [ with \ otherwise there is error
  2005. "ERROR: missing close-bracket" instead of real error
  2006. :param error: it may be text or exception
  2007. :return: None
  2008. """
  2009. if isinstance(error, Exception):
  2010. exc_type, exc_value, exc_traceback = error_info
  2011. if not isinstance(error, self.TclErrorException):
  2012. show_trace = 1
  2013. else:
  2014. show_trace = int(self.defaults['global_verbose_error_level'])
  2015. if show_trace > 0:
  2016. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2017. trc_formated = []
  2018. for a in reversed(trc):
  2019. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2020. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  2021. exc_type,
  2022. "\n".join(trc_formated))
  2023. else:
  2024. text = "%s" % error
  2025. else:
  2026. text = error
  2027. text = text.replace('[', '\\[').replace('"', '\\"')
  2028. self.tcl.eval('return -code error "%s"' % text)
  2029. def raise_tcl_error(self, text):
  2030. """
  2031. this method pass exception from python into TCL as error, so we get stacktrace and reason
  2032. :param text: text of error
  2033. :return: raise exception
  2034. """
  2035. self.display_tcl_error(text)
  2036. raise self.TclErrorException(text)
  2037. def exec_command(self, text):
  2038. """
  2039. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2040. Also handles execution in separated threads
  2041. :param text:
  2042. :return: output if there was any
  2043. """
  2044. self.report_usage('exec_command')
  2045. result = self.exec_command_test(text, False)
  2046. #MS: added this method call so the geometry is updated once the TCL
  2047. #command is executed
  2048. self.plot_all()
  2049. return result
  2050. def exec_command_test(self, text, reraise=True):
  2051. """
  2052. Same as exec_command(...) with additional control over exceptions.
  2053. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2054. :param text: Input command
  2055. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2056. :return: Output from the command
  2057. """
  2058. text = str(text)
  2059. try:
  2060. self.shell.open_proccessing() # Disables input box.
  2061. result = self.tcl.eval(str(text))
  2062. if result != 'None':
  2063. self.shell.append_output(result + '\n')
  2064. except tk.TclError as e:
  2065. # This will display more precise answer if something in TCL shell fails
  2066. result = self.tcl.eval("set errorInfo")
  2067. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2068. self.shell.append_error('ERROR: ' + result + '\n')
  2069. # Show error in console and just return or in test raise exception
  2070. if reraise:
  2071. raise e
  2072. finally:
  2073. self.shell.close_proccessing()
  2074. pass
  2075. return result
  2076. # """
  2077. # Code below is unsused. Saved for later.
  2078. # """
  2079. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2080. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2081. # self.log.debug(parts)
  2082. # try:
  2083. # if parts[0] not in commands:
  2084. # self.shell.append_error("Unknown command\n")
  2085. # return
  2086. #
  2087. # #import inspect
  2088. # #inspect.getargspec(someMethod)
  2089. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2090. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2091. # self.shell.append_error(
  2092. # "Command %s takes %d arguments. %d given.\n" %
  2093. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2094. # )
  2095. # return
  2096. #
  2097. # cmdfcn = commands[parts[0]]["fcn"]
  2098. # cmdconv = commands[parts[0]]["converters"]
  2099. # if len(parts) - 1 > 0:
  2100. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2101. # else:
  2102. # retval = cmdfcn()
  2103. # retfcn = commands[parts[0]]["retfcn"]
  2104. # if retval and retfcn(retval):
  2105. # self.shell.append_output(retfcn(retval) + "\n")
  2106. #
  2107. # except Exception as e:
  2108. # #self.shell.append_error(''.join(traceback.format_exc()))
  2109. # #self.shell.append_error("?\n")
  2110. # self.shell.append_error(str(e) + "\n")
  2111. def info(self, msg):
  2112. """
  2113. Informs the user. Normally on the status bar, optionally
  2114. also on the shell.
  2115. :param msg: Text to write.
  2116. :return: None
  2117. """
  2118. # Type of message in brackets at the begining of the message.
  2119. match = re.search("\[([^\]]+)\](.*)", msg)
  2120. if match:
  2121. level = match.group(1)
  2122. msg_ = match.group(2)
  2123. self.ui.fcinfo.set_status(str(msg_), level=level)
  2124. if level.lower() == "error":
  2125. self.shell_message(msg, error=True, show=True)
  2126. elif level.lower() == "warning":
  2127. self.shell_message(msg, warning=True, show=True)
  2128. elif level.lower() == "error_notcl":
  2129. self.shell_message(msg, error=True, show=False)
  2130. elif level.lower() == "warning_notcl":
  2131. self.shell_message(msg, warning=True, show=False)
  2132. elif level.lower() == "success":
  2133. self.shell_message(msg, success=True, show=False)
  2134. elif level.lower() == "selected":
  2135. self.shell_message(msg, selected=True, show=False)
  2136. else:
  2137. self.shell_message(msg, show=False)
  2138. else:
  2139. self.ui.fcinfo.set_status(str(msg), level="info")
  2140. # make sure that if the message is to clear the infobar with a space
  2141. # is not printed over and over on the shell
  2142. if msg != '':
  2143. self.shell_message(msg)
  2144. def restore_toolbar_view(self):
  2145. tb = self.defaults["global_toolbar_view"]
  2146. if tb & 1:
  2147. self.ui.toolbarfile.setVisible(True)
  2148. else:
  2149. self.ui.toolbarfile.setVisible(False)
  2150. if tb & 2:
  2151. self.ui.toolbargeo.setVisible(True)
  2152. else:
  2153. self.ui.toolbargeo.setVisible(False)
  2154. if tb & 4:
  2155. self.ui.toolbarview.setVisible(True)
  2156. else:
  2157. self.ui.toolbarview.setVisible(False)
  2158. if tb & 8:
  2159. self.ui.toolbartools.setVisible(True)
  2160. else:
  2161. self.ui.toolbartools.setVisible(False)
  2162. if tb & 16:
  2163. self.ui.exc_edit_toolbar.setVisible(True)
  2164. else:
  2165. self.ui.exc_edit_toolbar.setVisible(False)
  2166. if tb & 32:
  2167. self.ui.geo_edit_toolbar.setVisible(True)
  2168. else:
  2169. self.ui.geo_edit_toolbar.setVisible(False)
  2170. if tb & 64:
  2171. self.ui.grb_edit_toolbar.setVisible(True)
  2172. else:
  2173. self.ui.grb_edit_toolbar.setVisible(False)
  2174. if tb & 128:
  2175. self.ui.snap_toolbar.setVisible(True)
  2176. else:
  2177. self.ui.snap_toolbar.setVisible(False)
  2178. if tb & 256:
  2179. self.ui.toolbarshell.setVisible(True)
  2180. else:
  2181. self.ui.toolbarshell.setVisible(False)
  2182. def load_defaults(self, filename):
  2183. """
  2184. Loads the aplication's default settings from current_defaults.FlatConfig into
  2185. ``self.defaults``.
  2186. :return: None
  2187. """
  2188. try:
  2189. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2190. options = f.read()
  2191. f.close()
  2192. except IOError:
  2193. self.log.error("Could not load defaults file.")
  2194. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2195. # in case the defaults file can't be loaded, show all toolbars
  2196. self.defaults["global_toolbar_view"] = 511
  2197. return
  2198. try:
  2199. defaults = json.loads(options)
  2200. except:
  2201. # in case the defaults file can't be loaded, show all toolbars
  2202. self.defaults["global_toolbar_view"] = 511
  2203. e = sys.exc_info()[0]
  2204. App.log.error(str(e))
  2205. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2206. return
  2207. self.defaults.update(defaults)
  2208. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2209. # restore the toolbar view
  2210. self.restore_toolbar_view()
  2211. def on_import_preferences(self):
  2212. """
  2213. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2214. ``self.defaults``.
  2215. :return: None
  2216. """
  2217. self.report_usage("on_import_preferences")
  2218. App.log.debug("on_import_preferences()")
  2219. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2220. try:
  2221. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2222. directory=self.data_path, filter=filter)
  2223. except TypeError:
  2224. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filter=filter)
  2225. filename = str(filename)
  2226. if filename == "":
  2227. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2228. else:
  2229. try:
  2230. f = open(filename)
  2231. options = f.read()
  2232. f.close()
  2233. except IOError:
  2234. self.log.error("Could not load defaults file.")
  2235. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2236. return
  2237. try:
  2238. defaults_from_file = json.loads(options)
  2239. except:
  2240. e = sys.exc_info()[0]
  2241. App.log.error(str(e))
  2242. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2243. return
  2244. self.defaults.update(defaults_from_file)
  2245. self.inform.emit(_("[success] Imported Defaults from %s") %filename)
  2246. def on_export_preferences(self):
  2247. self.report_usage("on_export_preferences")
  2248. App.log.debug("on_export_preferences()")
  2249. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2250. try:
  2251. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2252. caption=_("Export FlatCAM Preferences"),
  2253. directory=self.data_path + '/preferences_' + self.date, filter=filter
  2254. )
  2255. except TypeError:
  2256. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"), filter=filter)
  2257. filename = str(filename)
  2258. defaults_from_file = {}
  2259. if filename == "":
  2260. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2261. return
  2262. else:
  2263. try:
  2264. f = open(filename, 'w')
  2265. defaults_file_content = f.read()
  2266. f.close()
  2267. except IOError:
  2268. App.log.debug('Creating a new preferences file ...')
  2269. f = open(filename, 'w')
  2270. json.dump({}, f)
  2271. f.close()
  2272. except:
  2273. e = sys.exc_info()[0]
  2274. App.log.error("Could not load defaults file.")
  2275. App.log.error(str(e))
  2276. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2277. return
  2278. try:
  2279. defaults_from_file = json.loads(defaults_file_content)
  2280. except:
  2281. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2282. # Update options
  2283. self.defaults_read_form()
  2284. defaults_from_file.update(self.defaults)
  2285. self.propagate_defaults(silent=True)
  2286. # Save update options
  2287. try:
  2288. f = open(filename, "w")
  2289. json.dump(defaults_from_file, f)
  2290. f.close()
  2291. except:
  2292. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2293. return
  2294. self.file_saved.emit("preferences", filename)
  2295. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2296. def on_preferences_open_folder(self):
  2297. self.report_usage("on_preferences_open_folder()")
  2298. if sys.platform == 'win32':
  2299. subprocess.Popen('explorer %s' % self.data_path)
  2300. elif sys.platform == 'darwin':
  2301. os.system('open "%s"' % self.data_path)
  2302. else:
  2303. subprocess.Popen(['xdg-open', self.data_path])
  2304. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2305. def save_geometry(self, x, y, width, height, notebook_width):
  2306. self.defaults["global_def_win_x"] = x
  2307. self.defaults["global_def_win_y"] = y
  2308. self.defaults["global_def_win_w"] = width
  2309. self.defaults["global_def_win_h"] = height
  2310. self.defaults["global_def_notebook_width"] = notebook_width
  2311. self.save_defaults()
  2312. def message_dialog(self, title, message, kind="info"):
  2313. icon = {"info": QtWidgets.QMessageBox.Information,
  2314. "warning": QtWidgets.QMessageBox.Warning,
  2315. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2316. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2317. dlg.setText(message)
  2318. dlg.exec_()
  2319. def register_recent(self, kind, filename):
  2320. self.log.debug("register_recent()")
  2321. self.log.debug(" %s" % kind)
  2322. self.log.debug(" %s" % filename)
  2323. record = {'kind': str(kind), 'filename': str(filename)}
  2324. if record in self.recent:
  2325. return
  2326. self.recent.insert(0, record)
  2327. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2328. self.recent.pop()
  2329. try:
  2330. f = open(self.data_path + '/recent.json', 'w')
  2331. except IOError:
  2332. App.log.error("Failed to open recent items file for writing.")
  2333. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2334. return
  2335. #try:
  2336. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2337. # except:
  2338. # App.log.error("Failed to write to recent items file.")
  2339. # self.inform.emit('ERROR: Failed to write to recent items file.')
  2340. # f.close()
  2341. f.close()
  2342. # Re-buid the recent items menu
  2343. self.setup_recent_items()
  2344. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2345. """
  2346. Creates a new specialized FlatCAMObj and attaches it to the application,
  2347. this is, updates the GUI accordingly, any other records and plots it.
  2348. This method is thread-safe.
  2349. Notes:
  2350. * If the name is in use, the self.collection will modify it
  2351. when appending it to the collection. There is no need to handle
  2352. name conflicts here.
  2353. :param kind: The kind of object to create. One of 'gerber',
  2354. 'excellon', 'cncjob' and 'geometry'.
  2355. :type kind: str
  2356. :param name: Name for the object.
  2357. :type name: str
  2358. :param initialize: Function to run after creation of the object
  2359. but before it is attached to the application. The function is
  2360. called with 2 parameters: the new object and the App instance.
  2361. :type initialize: function
  2362. :return: None
  2363. :rtype: None
  2364. """
  2365. App.log.debug("new_object()")
  2366. obj_plot = plot
  2367. obj_autoselected = autoselected
  2368. t0 = time.time() # Debug
  2369. ## Create object
  2370. classdict = {
  2371. "gerber": FlatCAMGerber,
  2372. "excellon": FlatCAMExcellon,
  2373. "cncjob": FlatCAMCNCjob,
  2374. "geometry": FlatCAMGeometry
  2375. }
  2376. App.log.debug("Calling object constructor...")
  2377. obj = classdict[kind](name)
  2378. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2379. # Set options from "Project options" form
  2380. self.options_read_form()
  2381. # IMPORTANT
  2382. # The key names in defaults and options dictionary's are not random:
  2383. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2384. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2385. # the options from project options form into the self.options. After that, below, depending on the type of
  2386. # object that is created, it will strip the name of the object and the underline (if the original key was
  2387. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2388. # "toolchange"
  2389. for option in self.options:
  2390. if option.find(kind + "_") == 0:
  2391. oname = option[len(kind) + 1:]
  2392. obj.options[oname] = self.options[option]
  2393. obj.isHovering = False
  2394. obj.notHovering = True
  2395. # Initialize as per user request
  2396. # User must take care to implement initialize
  2397. # in a thread-safe way as is is likely that we
  2398. # have been invoked in a separate thread.
  2399. t1 = time.time()
  2400. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2401. try:
  2402. return_value = initialize(obj, self)
  2403. except Exception as e:
  2404. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2405. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2406. msg += traceback.format_exc()
  2407. self.inform.emit(msg)
  2408. # if str(e) == "Empty Geometry":
  2409. # self.inform.emit("[ERROR_NOTCL] )
  2410. # else:
  2411. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2412. return "fail"
  2413. t2 = time.time()
  2414. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2415. if return_value == 'fail':
  2416. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2417. return "fail"
  2418. # Check units and convert if necessary
  2419. # This condition CAN be true because initialize() can change obj.units
  2420. if self.options["units"].upper() != obj.units.upper():
  2421. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2422. obj.convert_units(self.options["units"])
  2423. t3 = time.time()
  2424. self.log.debug("%f seconds converting units." % (t3 - t2))
  2425. # Create the bounding box for the object and then add the results to the obj.options
  2426. try:
  2427. xmin, ymin, xmax, ymax = obj.bounds()
  2428. obj.options['xmin'] = xmin
  2429. obj.options['ymin'] = ymin
  2430. obj.options['xmax'] = xmax
  2431. obj.options['ymax'] = ymax
  2432. except:
  2433. log.warning("The object has no bounds properties.")
  2434. # don't plot objects with no bounds, there is nothing to plot
  2435. self.plot = False
  2436. pass
  2437. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2438. # Move the object to the main thread and let the app know that it is available.
  2439. obj.moveToThread(self.main_thread)
  2440. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2441. return obj
  2442. def new_excellon_object(self):
  2443. self.report_usage("new_excellon_object()")
  2444. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2445. def new_geometry_object(self):
  2446. self.report_usage("new_geometry_object()")
  2447. def initialize(obj, self):
  2448. obj.multitool = False
  2449. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2450. def new_gerber_object(self):
  2451. self.report_usage("new_gerber_object()")
  2452. def initialize(grb_obj, self):
  2453. grb_obj.multitool = False
  2454. grb_obj.source_file = []
  2455. grb_obj.multigeo = False
  2456. grb_obj.follow = False
  2457. grb_obj.apertures = {}
  2458. try:
  2459. grb_obj.options['xmin'] = 0
  2460. grb_obj.options['ymin'] = 0
  2461. grb_obj.options['xmax'] = 0
  2462. grb_obj.options['ymax'] = 0
  2463. except KeyError:
  2464. pass
  2465. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2466. def on_object_created(self, obj, plot, autoselect):
  2467. """
  2468. Event callback for object creation.
  2469. :param obj: The newly created FlatCAM object.
  2470. :return: None
  2471. """
  2472. t0 = time.time() # DEBUG
  2473. self.log.debug("on_object_created()")
  2474. # The Collection might change the name if there is a collision
  2475. self.collection.append(obj)
  2476. # after adding the object to the collection always update the list of objects that are in the collection
  2477. self.all_objects_list = self.collection.get_list()
  2478. # self.inform.emit('[selected] %s created & selected: %s' %
  2479. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2480. if obj.kind == 'gerber':
  2481. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2482. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2483. elif obj.kind == 'excellon':
  2484. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2485. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2486. elif obj.kind == 'cncjob':
  2487. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2488. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2489. elif obj.kind == 'geometry':
  2490. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2491. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2492. # update the SHELL auto-completer model with the name of the new object
  2493. self.myKeywords.append(obj.options['name'])
  2494. self.shell._edit.set_model_data(self.myKeywords)
  2495. self.ui.code_editor.set_model_data(self.myKeywords)
  2496. if autoselect:
  2497. # select the just opened object but deselect the previous ones
  2498. self.collection.set_all_inactive()
  2499. self.collection.set_active(obj.options["name"])
  2500. # here it is done the object plotting
  2501. def worker_task(obj):
  2502. with self.proc_container.new("Plotting"):
  2503. if isinstance(obj, FlatCAMCNCjob):
  2504. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2505. else:
  2506. obj.plot()
  2507. t1 = time.time() # DEBUG
  2508. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2509. self.object_plotted.emit(obj)
  2510. # Send to worker
  2511. # self.worker.add_task(worker_task, [self])
  2512. if plot is True:
  2513. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2514. def on_object_changed(self, obj):
  2515. # update the bounding box data from obj.options
  2516. xmin, ymin, xmax, ymax = obj.bounds()
  2517. obj.options['xmin'] = xmin
  2518. obj.options['ymin'] = ymin
  2519. obj.options['xmax'] = xmax
  2520. obj.options['ymax'] = ymax
  2521. log.debug("Object changed, updating the bounding box data on self.options")
  2522. # delete the old selection shape
  2523. self.delete_selection_shape()
  2524. self.should_we_save = True
  2525. def on_object_plotted(self, obj):
  2526. self.on_zoom_fit(None)
  2527. def options_read_form(self):
  2528. for option in self.options_form_fields:
  2529. self.options[option] = self.options_form_fields[option].get_value()
  2530. def options_write_form(self):
  2531. for option in self.options:
  2532. self.options_write_form_field(option)
  2533. def options_write_form_field(self, field):
  2534. try:
  2535. self.options_form_fields[field].set_value(self.options[field])
  2536. except KeyError:
  2537. # Changed from error to debug. This allows to have data stored
  2538. # which is not user-editable.
  2539. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2540. pass
  2541. def on_about(self):
  2542. """
  2543. Displays the "about" dialog.
  2544. :return: None
  2545. """
  2546. self.report_usage("on_about")
  2547. version = self.version
  2548. version_date = self.version_date
  2549. beta = self.beta
  2550. class AboutDialog(QtWidgets.QDialog):
  2551. def __init__(self, parent=None):
  2552. QtWidgets.QDialog.__init__(self, parent)
  2553. # Icon and title
  2554. self.setWindowIcon(parent.app_icon)
  2555. self.setWindowTitle("FlatCAM")
  2556. layout1 = QtWidgets.QVBoxLayout()
  2557. self.setLayout(layout1)
  2558. layout2 = QtWidgets.QHBoxLayout()
  2559. layout1.addLayout(layout2)
  2560. logo = QtWidgets.QLabel()
  2561. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2562. layout2.addWidget(logo, stretch=0)
  2563. title = QtWidgets.QLabel(
  2564. _(
  2565. "<font size=8><B>FlatCAM</B></font><BR>"
  2566. "Version {version} {beta} ({date}) - {arch} <BR>"
  2567. "<BR>"
  2568. "2D Computer-Aided Printed Circuit Board<BR>"
  2569. "Manufacturing.<BR>"
  2570. "<BR>"
  2571. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2572. "<BR>"
  2573. "<B> Main Contributors:</B><BR>"
  2574. "Denis Hayrullin<BR>"
  2575. "Kamil Sopko<BR>"
  2576. "Marius Stanciu<BR>"
  2577. "Matthieu Berthomé<BR>"
  2578. "and many others found "
  2579. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2580. "<BR>"
  2581. "Development is done "
  2582. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2583. "DOWNLOAD area "
  2584. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2585. ""
  2586. ).format(version=version,
  2587. beta=('BETA' if beta else ''),
  2588. date=version_date,
  2589. arch=platform.architecture()[0])
  2590. )
  2591. title.setOpenExternalLinks(True)
  2592. layout2.addWidget(title, stretch=1)
  2593. layout3 = QtWidgets.QHBoxLayout()
  2594. layout1.addLayout(layout3)
  2595. layout3.addStretch()
  2596. okbtn = QtWidgets.QPushButton("Close")
  2597. layout3.addWidget(okbtn)
  2598. okbtn.clicked.connect(self.accept)
  2599. AboutDialog(self.ui).exec_()
  2600. def on_file_savedefaults(self):
  2601. """
  2602. Callback for menu item File->Save Defaults. Saves application default options
  2603. ``self.defaults`` to current_defaults.FlatConfig.
  2604. :return: None
  2605. """
  2606. self.save_defaults()
  2607. # def on_app_exit(self):
  2608. # self.report_usage("on_app_exit()")
  2609. #
  2610. # if self.collection.get_list():
  2611. # msgbox = QtWidgets.QMessageBox()
  2612. # # msgbox.setText("<B>Save changes ...</B>")
  2613. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2614. # "\n"
  2615. # "Do you want to Save the project?")
  2616. # msgbox.setWindowTitle("Save changes")
  2617. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2618. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2619. # QtWidgets.QMessageBox.Cancel)
  2620. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2621. #
  2622. # response = msgbox.exec_()
  2623. #
  2624. # if response == QtWidgets.QMessageBox.Yes:
  2625. # self.on_file_saveprojectas(thread=False)
  2626. # elif response == QtWidgets.QMessageBox.Cancel:
  2627. # return
  2628. # self.save_defaults()
  2629. # else:
  2630. # self.save_defaults()
  2631. # log.debug("Application defaults saved ... Exit event.")
  2632. # QtWidgets.qApp.quit()
  2633. def save_defaults(self, silent=False):
  2634. """
  2635. Saves application default options
  2636. ``self.defaults`` to current_defaults.FlatConfig.
  2637. :return: None
  2638. """
  2639. self.report_usage("save_defaults")
  2640. # Read options from file
  2641. try:
  2642. f = open(self.data_path + "/current_defaults.FlatConfig")
  2643. defaults_file_content = f.read()
  2644. f.close()
  2645. except:
  2646. e = sys.exc_info()[0]
  2647. App.log.error("Could not load defaults file.")
  2648. App.log.error(str(e))
  2649. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2650. return
  2651. try:
  2652. defaults = json.loads(defaults_file_content)
  2653. except:
  2654. e = sys.exc_info()[0]
  2655. App.log.error("Failed to parse defaults file.")
  2656. App.log.error(str(e))
  2657. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2658. return
  2659. # Update options
  2660. self.defaults_read_form()
  2661. defaults.update(self.defaults)
  2662. self.propagate_defaults(silent=True)
  2663. # Save the toolbar view
  2664. tb_status = 0
  2665. if self.ui.toolbarfile.isVisible():
  2666. tb_status += 1
  2667. if self.ui.toolbargeo.isVisible():
  2668. tb_status += 2
  2669. if self.ui.toolbarview.isVisible():
  2670. tb_status += 4
  2671. if self.ui.toolbartools.isVisible():
  2672. tb_status += 8
  2673. if self.ui.exc_edit_toolbar.isVisible():
  2674. tb_status += 16
  2675. if self.ui.geo_edit_toolbar.isVisible():
  2676. tb_status += 32
  2677. if self.ui.grb_edit_toolbar.isVisible():
  2678. tb_status += 64
  2679. if self.ui.snap_toolbar.isVisible():
  2680. tb_status += 128
  2681. if self.ui.toolbarshell.isVisible():
  2682. tb_status += 256
  2683. self.defaults["global_toolbar_view"] = tb_status
  2684. # Save update options
  2685. try:
  2686. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2687. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2688. f.close()
  2689. except:
  2690. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2691. return
  2692. if not silent:
  2693. self.inform.emit(_("[success] Defaults saved."))
  2694. def save_factory_defaults(self, silent=False):
  2695. """
  2696. Saves application factory default options
  2697. ``self.defaults`` to factory_defaults.FlatConfig.
  2698. It's a one time job done just after the first install.
  2699. :return: None
  2700. """
  2701. self.report_usage("save_factory_defaults")
  2702. # Read options from file
  2703. try:
  2704. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2705. factory_defaults_file_content = f_f_def.read()
  2706. f_f_def.close()
  2707. except:
  2708. e = sys.exc_info()[0]
  2709. App.log.error("Could not load factory defaults file.")
  2710. App.log.error(str(e))
  2711. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2712. return
  2713. try:
  2714. factory_defaults = json.loads(factory_defaults_file_content)
  2715. except:
  2716. e = sys.exc_info()[0]
  2717. App.log.error("Failed to parse factory defaults file.")
  2718. App.log.error(str(e))
  2719. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2720. return
  2721. # Update options
  2722. self.defaults_read_form()
  2723. factory_defaults.update(self.defaults)
  2724. self.propagate_defaults(silent=True)
  2725. # Save update options
  2726. try:
  2727. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2728. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2729. f_f_def_s.close()
  2730. except:
  2731. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2732. return
  2733. if silent is False:
  2734. self.inform.emit(_("Factory defaults saved."))
  2735. def final_save(self):
  2736. if self.save_in_progress:
  2737. self.inform.emit(_("[WARNING_NOTCL] Application is saving the project. Please wait ..."))
  2738. return
  2739. if self.should_we_save and self.collection.get_list():
  2740. msgbox = QtWidgets.QMessageBox()
  2741. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2742. "\n"
  2743. "Do you want to Save the project?"))
  2744. msgbox.setWindowTitle(_("Save changes"))
  2745. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2746. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2747. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2748. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2749. msgbox.setDefaultButton(bt_yes)
  2750. msgbox.exec_()
  2751. response = msgbox.clickedButton()
  2752. if response == bt_yes:
  2753. self.on_file_saveprojectas(thread=True, quit=True)
  2754. elif response == bt_no:
  2755. self.quit_application()
  2756. elif response == bt_cancel:
  2757. return
  2758. else:
  2759. self.quit_application()
  2760. def quit_application(self):
  2761. self.save_defaults()
  2762. log.debug("App.final_save() --> App Defaults saved.")
  2763. # save toolbar state to file
  2764. settings = QSettings("Open Source", "FlatCAM")
  2765. settings.setValue('saved_gui_state', self.ui.saveState())
  2766. settings.setValue('maximized_gui', self.ui.isMaximized())
  2767. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  2768. # This will write the setting to the platform specific storage.
  2769. del settings
  2770. log.debug("App.final_save() --> App UI state saved.")
  2771. QtWidgets.qApp.quit()
  2772. def on_toggle_shell(self):
  2773. """
  2774. toggle shell if is visible close it if closed open it
  2775. :return:
  2776. """
  2777. self.report_usage("on_toggle_shell()")
  2778. if self.ui.shell_dock.isVisible():
  2779. self.ui.shell_dock.hide()
  2780. else:
  2781. self.ui.shell_dock.show()
  2782. def on_edit_join(self, name=None):
  2783. """
  2784. Callback for Edit->Join. Joins the selected geometry objects into
  2785. a new one.
  2786. :return: None
  2787. """
  2788. self.report_usage("on_edit_join()")
  2789. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2790. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2791. tooldias = []
  2792. geo_type_list = []
  2793. objs = self.collection.get_selected()
  2794. for obj in objs:
  2795. geo_type_list.append(obj.multigeo)
  2796. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2797. if len(set(geo_type_list)) != 1:
  2798. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2799. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2800. "convert from one to another and retry joining \n"
  2801. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2802. "the result may not be what was expected. \n"
  2803. "Check the generated GCODE."))
  2804. return
  2805. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2806. if True in geo_type_list:
  2807. def initialize(obj, app):
  2808. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2809. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2810. for v in obj.tools.values():
  2811. v['data']['name'] = obj_name_multi
  2812. self.new_object("geometry", obj_name_multi, initialize)
  2813. else:
  2814. def initialize(obj, app):
  2815. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2816. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2817. for v in obj.tools.values():
  2818. v['data']['name'] = obj_name_single
  2819. self.new_object("geometry", obj_name_single, initialize)
  2820. self.should_we_save = True
  2821. def on_edit_join_exc(self):
  2822. """
  2823. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2824. a new one.
  2825. :return: None
  2826. """
  2827. self.report_usage("on_edit_join_exc()")
  2828. objs = self.collection.get_selected()
  2829. for obj in objs:
  2830. if not isinstance(obj, FlatCAMExcellon):
  2831. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  2832. return
  2833. def initialize(obj, app):
  2834. FlatCAMExcellon.merge(objs, obj)
  2835. self.new_object("excellon", 'Combo_Excellon', initialize)
  2836. self.should_we_save = True
  2837. def on_edit_join_grb(self):
  2838. """
  2839. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2840. a new one.
  2841. :return: None
  2842. """
  2843. self.report_usage("on_edit_join_grb()")
  2844. objs = self.collection.get_selected()
  2845. for obj in objs:
  2846. if not isinstance(obj, FlatCAMGerber):
  2847. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  2848. return
  2849. def initialize(obj, app):
  2850. FlatCAMGerber.merge(objs, obj)
  2851. self.new_object("gerber", 'Combo_Gerber', initialize)
  2852. self.should_we_save = True
  2853. def on_convert_singlegeo_to_multigeo(self):
  2854. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2855. obj = self.collection.get_active()
  2856. if obj is None:
  2857. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2858. return
  2859. if not isinstance(obj, FlatCAMGeometry):
  2860. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2861. return
  2862. obj.multigeo = True
  2863. for tooluid, dict_value in obj.tools.items():
  2864. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2865. if not isinstance(obj.solid_geometry, list):
  2866. obj.solid_geometry = [obj.solid_geometry]
  2867. obj.solid_geometry[:] = []
  2868. obj.plot()
  2869. self.should_we_save = True
  2870. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2871. def on_convert_multigeo_to_singlegeo(self):
  2872. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2873. obj = self.collection.get_active()
  2874. if obj is None:
  2875. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2876. return
  2877. if not isinstance(obj, FlatCAMGeometry):
  2878. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2879. return
  2880. obj.multigeo = False
  2881. total_solid_geometry = []
  2882. for tooluid, dict_value in obj.tools.items():
  2883. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2884. # clear the original geometry
  2885. dict_value['solid_geometry'][:] = []
  2886. obj.solid_geometry = deepcopy(total_solid_geometry)
  2887. obj.plot()
  2888. self.should_we_save = True
  2889. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2890. def on_options_dict_change(self, field):
  2891. self.options_write_form_field(field)
  2892. if field == "units":
  2893. self.set_screen_units(self.options['units'])
  2894. def on_defaults_dict_change(self, field):
  2895. self.defaults_write_form_field(field)
  2896. if field == "units":
  2897. self.set_screen_units(self.defaults['units'])
  2898. def set_screen_units(self, units):
  2899. self.ui.units_label.setText("[" + self.defaults["units"].lower() + "]")
  2900. def on_toggle_units(self):
  2901. """
  2902. Callback for the Units radio-button change in the Options tab.
  2903. Changes the application's default units or the current project's units.
  2904. If changing the project's units, the change propagates to all of
  2905. the objects in the project.
  2906. :return: None
  2907. """
  2908. self.report_usage("on_toggle_units")
  2909. if self.toggle_units_ignore:
  2910. return
  2911. # If option is the same, then ignore
  2912. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2913. self.defaults["units"].upper():
  2914. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2915. return
  2916. # Options to scale
  2917. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2918. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2919. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2920. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2921. "excellon_z_pdepth",
  2922. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2923. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2924. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2925. "geometry_feedrate_probe",
  2926. 'cncjob_tooldia',
  2927. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2928. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2929. "tools_2sided_drilldia", "tools_film_boundary",
  2930. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2931. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2932. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  2933. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  2934. "tools_transform_offset_y",
  2935. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  2936. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  2937. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  2938. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  2939. 'global_gridx', 'global_gridy', 'global_snap_max']
  2940. def scale_options(sfactor):
  2941. for dim in dimensions:
  2942. if dim == 'excellon_toolchangexy':
  2943. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2944. coords_xy[0] *= sfactor
  2945. coords_xy[1] *= sfactor
  2946. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2947. elif dim == 'geometry_toolchangexy':
  2948. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2949. coords_xy[0] *= sfactor
  2950. coords_xy[1] *= sfactor
  2951. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2952. elif dim == 'tools_ncctools':
  2953. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2954. ncctols[0] *= sfactor
  2955. ncctols[1] *= sfactor
  2956. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  2957. elif dim == 'tools_solderpaste_tools':
  2958. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2959. sp_tools[0] *= sfactor
  2960. sp_tools[1] *= sfactor
  2961. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  2962. elif dim == 'tools_solderpaste_xy_toolchange':
  2963. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2964. sp_coords[0] *= sfactor
  2965. sp_coords[1] *= sfactor
  2966. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  2967. else:
  2968. try:
  2969. self.options[dim] = float(self.options[dim]) * sfactor
  2970. except Exception as e:
  2971. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  2972. def scale_defaults(sfactor):
  2973. for dim in dimensions:
  2974. if dim == 'excellon_toolchangexy':
  2975. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2976. coords_xy[0] *= sfactor
  2977. coords_xy[1] *= sfactor
  2978. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2979. elif dim == 'geometry_toolchangexy':
  2980. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2981. coords_xy[0] *= sfactor
  2982. coords_xy[1] *= sfactor
  2983. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2984. elif dim == 'tools_ncctools':
  2985. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2986. ncctols[0] *= sfactor
  2987. ncctols[1] *= sfactor
  2988. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  2989. elif dim == 'tools_solderpaste_tools':
  2990. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2991. sp_tools[0] *= sfactor
  2992. sp_tools[1] *= sfactor
  2993. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  2994. elif dim == 'tools_solderpaste_xy_toolchange':
  2995. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2996. sp_coords[0] *= sfactor
  2997. sp_coords[1] *= sfactor
  2998. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  2999. else:
  3000. try:
  3001. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  3002. except Exception as e:
  3003. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3004. # The scaling factor depending on choice of units.
  3005. factor = 1/25.4
  3006. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3007. factor = 25.4
  3008. # Changing project units. Warn user.
  3009. msgbox = QtWidgets.QMessageBox()
  3010. msgbox.setWindowTitle("Toggle Units")
  3011. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  3012. msgbox.setText("<B>Change project units ...</B>")
  3013. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  3014. "properties of all objects to be scaled accordingly.\nContinue?")
  3015. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3016. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3017. msgbox.setDefaultButton(bt_ok)
  3018. msgbox.exec_()
  3019. response = msgbox.clickedButton()
  3020. if response == bt_ok:
  3021. self.options_read_form()
  3022. scale_options(factor)
  3023. self.options_write_form()
  3024. self.defaults_read_form()
  3025. scale_defaults(factor)
  3026. self.defaults_write_form()
  3027. self.should_we_save = True
  3028. # change this only if the workspace is active
  3029. if self.defaults['global_workspace'] is True:
  3030. self.plotcanvas.draw_workspace()
  3031. # adjust the grid values on the main toolbar
  3032. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  3033. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  3034. for obj in self.collection.get_list():
  3035. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3036. obj.convert_units(units)
  3037. # make that the properties stored in the object are also updated
  3038. self.object_changed.emit(obj)
  3039. obj.build_ui()
  3040. current = self.collection.get_active()
  3041. if current is not None:
  3042. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3043. if not isinstance(current, FlatCAMGeometry):
  3044. current.to_form()
  3045. self.plot_all()
  3046. self.inform.emit(_("[success] Converted units to %s") % self.defaults["units"])
  3047. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  3048. self.set_screen_units(self.defaults["units"])
  3049. else:
  3050. # Undo toggling
  3051. self.toggle_units_ignore = True
  3052. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  3053. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3054. else:
  3055. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3056. self.toggle_units_ignore = False
  3057. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  3058. self.options_read_form()
  3059. self.defaults_read_form()
  3060. def on_toggle_units_click(self):
  3061. if self.options["units"] == 'MM':
  3062. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3063. else:
  3064. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3065. self.on_toggle_units()
  3066. def on_fullscreen(self):
  3067. self.report_usage("on_fullscreen()")
  3068. if self.toggle_fscreen is False:
  3069. if sys.platform == 'win32':
  3070. self.ui.showFullScreen()
  3071. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3072. tb.setVisible(False)
  3073. self.ui.splitter_left.setVisible(False)
  3074. self.toggle_fscreen = True
  3075. else:
  3076. if sys.platform == 'win32':
  3077. self.ui.showNormal()
  3078. self.restore_toolbar_view()
  3079. self.ui.splitter_left.setVisible(True)
  3080. self.toggle_fscreen = False
  3081. def on_toggle_plotarea(self):
  3082. self.report_usage("on_toggle_plotarea()")
  3083. try:
  3084. name = self.ui.plot_tab_area.widget(0).objectName()
  3085. except AttributeError:
  3086. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3087. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3088. self.ui.plot_tab_area.protectTab(0)
  3089. return
  3090. if name != 'plotarea':
  3091. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3092. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3093. self.ui.plot_tab_area.protectTab(0)
  3094. else:
  3095. self.ui.plot_tab_area.closeTab(0)
  3096. def on_toggle_notebook(self):
  3097. if self.ui.splitter.sizes()[0] == 0:
  3098. self.ui.splitter.setSizes([1, 1])
  3099. else:
  3100. self.ui.splitter.setSizes([0, 1])
  3101. def on_toggle_axis(self):
  3102. self.report_usage("on_toggle_axis()")
  3103. if self.toggle_axis is False:
  3104. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3105. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3106. self.plotcanvas.redraw()
  3107. self.toggle_axis = True
  3108. else:
  3109. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3110. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3111. self.plotcanvas.redraw()
  3112. self.toggle_axis = False
  3113. def on_toggle_grid(self):
  3114. self.report_usage("on_toggle_grid()")
  3115. self.ui.grid_snap_btn.trigger()
  3116. def on_options_combo_change(self, sel):
  3117. """
  3118. Called when the combo box to choose between application defaults and
  3119. project option changes value. The corresponding variables are
  3120. copied to the UI.
  3121. :param sel: The option index that was chosen.
  3122. :return: None
  3123. """
  3124. # combo_sel = self.ui.notebook.combo_options.get_active()
  3125. App.log.debug("Options --> %s" % sel)
  3126. # form = [self.defaults_form, self.options_form][sel]
  3127. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3128. if sel == 0:
  3129. self.gen_form = self.ui.general_defaults_form
  3130. self.ger_form = self.ui.gerber_defaults_form
  3131. self.exc_form = self.ui.excellon_defaults_form
  3132. self.geo_form = self.ui.geometry_defaults_form
  3133. self.cnc_form = self.ui.cncjob_defaults_form
  3134. self.tools_form = self.ui.tools_defaults_form
  3135. elif sel == 1:
  3136. self.gen_form = self.ui.general_options_form
  3137. self.ger_form = self.ui.gerber_options_form
  3138. self.exc_form = self.ui.excellon_options_form
  3139. self.geo_form = self.ui.geometry_options_form
  3140. self.cnc_form = self.ui.cncjob_options_form
  3141. self.tools_form = self.ui.tools_options_form
  3142. else:
  3143. return
  3144. try:
  3145. self.ui.general_scroll_area.takeWidget()
  3146. except:
  3147. self.log.debug("Nothing to remove")
  3148. self.ui.general_scroll_area.setWidget(self.gen_form)
  3149. self.gen_form.show()
  3150. try:
  3151. self.ui.gerber_scroll_area.takeWidget()
  3152. except:
  3153. self.log.debug("Nothing to remove")
  3154. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3155. self.ger_form.show()
  3156. try:
  3157. self.ui.excellon_scroll_area.takeWidget()
  3158. except:
  3159. self.log.debug("Nothing to remove")
  3160. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3161. self.exc_form.show()
  3162. try:
  3163. self.ui.geometry_scroll_area.takeWidget()
  3164. except:
  3165. self.log.debug("Nothing to remove")
  3166. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3167. self.geo_form.show()
  3168. try:
  3169. self.ui.cncjob_scroll_area.takeWidget()
  3170. except:
  3171. self.log.debug("Nothing to remove")
  3172. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3173. self.cnc_form.show()
  3174. try:
  3175. self.ui.tools_scroll_area.takeWidget()
  3176. except:
  3177. self.log.debug("Nothing to remove")
  3178. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3179. self.tools_form.show()
  3180. self.log.debug("Finished GUI form initialization.")
  3181. # self.options2form()
  3182. def on_excellon_defaults_button(self):
  3183. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3184. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3185. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3186. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3187. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3188. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3189. log.debug("Excellon app defaults loaded ...")
  3190. def on_excellon_options_button(self):
  3191. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3192. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3193. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3194. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3195. self.options_form_fields["excellon_zeros"].set_value('L')
  3196. self.options_form_fields["excellon_units"].set_value('INCH')
  3197. log.debug("Excellon options defaults loaded ...")
  3198. # Setting plot colors handlers
  3199. def on_pf_color_entry(self):
  3200. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3201. self.defaults['global_plot_fill'][7:9]
  3202. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3203. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3204. def on_pf_color_button(self):
  3205. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3206. c_dialog = QtWidgets.QColorDialog()
  3207. plot_fill_color = c_dialog.getColor(initial=current_color)
  3208. if plot_fill_color.isValid() is False:
  3209. return
  3210. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3211. "background-color:%s" % str(plot_fill_color.name()))
  3212. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3213. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3214. self.defaults['global_plot_fill'] = new_val
  3215. def on_pf_color_spinner(self):
  3216. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3217. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3218. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  3219. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3220. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  3221. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3222. def on_pf_color_slider(self):
  3223. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3224. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3225. def on_pl_color_entry(self):
  3226. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3227. self.defaults['global_plot_line'][7:9]
  3228. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3229. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3230. def on_pl_color_button(self):
  3231. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3232. # print(current_color)
  3233. c_dialog = QtWidgets.QColorDialog()
  3234. plot_line_color = c_dialog.getColor(initial=current_color)
  3235. if plot_line_color.isValid() is False:
  3236. return
  3237. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3238. "background-color:%s" % str(plot_line_color.name()))
  3239. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3240. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3241. self.defaults['global_plot_line'] = new_val_line
  3242. # Setting selection colors (left - right) handlers
  3243. def on_sf_color_entry(self):
  3244. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3245. self.defaults['global_sel_fill'][7:9]
  3246. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3247. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3248. def on_sf_color_button(self):
  3249. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3250. c_dialog = QtWidgets.QColorDialog()
  3251. plot_fill_color = c_dialog.getColor(initial=current_color)
  3252. if plot_fill_color.isValid() is False:
  3253. return
  3254. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3255. "background-color:%s" % str(plot_fill_color.name()))
  3256. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3257. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3258. self.defaults['global_sel_fill'] = new_val
  3259. def on_sf_color_spinner(self):
  3260. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3261. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3262. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  3263. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3264. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  3265. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3266. def on_sf_color_slider(self):
  3267. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3268. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3269. def on_sl_color_entry(self):
  3270. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3271. self.defaults['global_sel_line'][7:9]
  3272. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3273. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3274. def on_sl_color_button(self):
  3275. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3276. c_dialog = QtWidgets.QColorDialog()
  3277. plot_line_color = c_dialog.getColor(initial=current_color)
  3278. if plot_line_color.isValid() is False:
  3279. return
  3280. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3281. "background-color:%s" % str(plot_line_color.name()))
  3282. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3283. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3284. self.defaults['global_sel_line'] = new_val_line
  3285. # Setting selection colors (right - left) handlers
  3286. def on_alt_sf_color_entry(self):
  3287. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3288. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3289. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3290. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3291. def on_alt_sf_color_button(self):
  3292. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3293. c_dialog = QtWidgets.QColorDialog()
  3294. plot_fill_color = c_dialog.getColor(initial=current_color)
  3295. if plot_fill_color.isValid() is False:
  3296. return
  3297. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3298. "background-color:%s" % str(plot_fill_color.name()))
  3299. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3300. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3301. self.defaults['global_alt_sel_fill'] = new_val
  3302. def on_alt_sf_color_spinner(self):
  3303. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3304. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3305. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  3306. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3307. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  3308. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3309. def on_alt_sf_color_slider(self):
  3310. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3311. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3312. def on_alt_sl_color_entry(self):
  3313. self.defaults['global_alt_sel_line'] = self.ui.general_defaults_form.general_gui_group \
  3314. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  3315. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3316. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3317. def on_alt_sl_color_button(self):
  3318. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3319. c_dialog = QtWidgets.QColorDialog()
  3320. plot_line_color = c_dialog.getColor(initial=current_color)
  3321. if plot_line_color.isValid() is False:
  3322. return
  3323. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3324. "background-color:%s" % str(plot_line_color.name()))
  3325. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3326. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3327. self.defaults['global_alt_sel_line'] = new_val_line
  3328. # Setting Editor colors
  3329. def on_draw_color_entry(self):
  3330. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3331. .draw_color_entry.get_value()
  3332. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3333. "background-color:%s" % str(self.defaults['global_draw_color']))
  3334. def on_draw_color_button(self):
  3335. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3336. c_dialog = QtWidgets.QColorDialog()
  3337. draw_color = c_dialog.getColor(initial=current_color)
  3338. if draw_color.isValid() is False:
  3339. return
  3340. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3341. "background-color:%s" % str(draw_color.name()))
  3342. new_val = str(draw_color.name())
  3343. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3344. self.defaults['global_draw_color'] = new_val
  3345. def on_sel_draw_color_entry(self):
  3346. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3347. .sel_draw_color_entry.get_value()
  3348. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3349. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3350. def on_sel_draw_color_button(self):
  3351. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3352. c_dialog = QtWidgets.QColorDialog()
  3353. sel_draw_color = c_dialog.getColor(initial=current_color)
  3354. if sel_draw_color.isValid() is False:
  3355. return
  3356. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3357. "background-color:%s" % str(sel_draw_color.name()))
  3358. new_val_sel = str(sel_draw_color.name())
  3359. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3360. self.defaults['global_sel_draw_color'] = new_val_sel
  3361. def on_proj_color_entry(self):
  3362. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  3363. .proj_color_entry.get_value()
  3364. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3365. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  3366. def on_proj_color_button(self):
  3367. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  3368. c_dialog = QtWidgets.QColorDialog()
  3369. proj_color = c_dialog.getColor(initial=current_color)
  3370. if proj_color.isValid() is False:
  3371. return
  3372. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  3373. "background-color:%s" % str(proj_color.name()))
  3374. new_val_sel = str(proj_color.name())
  3375. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  3376. self.defaults['global_proj_item_color'] = new_val_sel
  3377. def on_deselect_all(self):
  3378. self.collection.set_all_inactive()
  3379. self.delete_selection_shape()
  3380. def on_workspace_modified(self):
  3381. self.save_defaults(silent=True)
  3382. self.plotcanvas.draw_workspace()
  3383. def on_workspace(self):
  3384. self.report_usage("on_workspace()")
  3385. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3386. self.plotcanvas.restore_workspace()
  3387. else:
  3388. self.plotcanvas.delete_workspace()
  3389. self.save_defaults(silent=True)
  3390. def on_workspace_menu(self):
  3391. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3392. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3393. else:
  3394. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3395. self.on_workspace()
  3396. def on_layout(self, index=None, lay=None):
  3397. self.report_usage("on_layout()")
  3398. if lay:
  3399. current_layout = lay
  3400. else:
  3401. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3402. settings = QSettings("Open Source", "FlatCAM")
  3403. settings.setValue('layout', current_layout)
  3404. # This will write the setting to the platform specific storage.
  3405. del settings
  3406. # first remove the toolbars:
  3407. try:
  3408. self.ui.removeToolBar(self.ui.toolbarfile)
  3409. self.ui.removeToolBar(self.ui.toolbargeo)
  3410. self.ui.removeToolBar(self.ui.toolbarview)
  3411. self.ui.removeToolBar(self.ui.toolbarshell)
  3412. self.ui.removeToolBar(self.ui.toolbartools)
  3413. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3414. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3415. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3416. self.ui.removeToolBar(self.ui.snap_toolbar)
  3417. self.ui.removeToolBar(self.ui.toolbarshell)
  3418. except:
  3419. pass
  3420. if current_layout == 'standard':
  3421. ### TOOLBAR INSTALLATION ###
  3422. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3423. self.ui.toolbarfile.setObjectName('File_TB')
  3424. self.ui.addToolBar(self.ui.toolbarfile)
  3425. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3426. self.ui.toolbargeo.setObjectName('Edit_TB')
  3427. self.ui.addToolBar(self.ui.toolbargeo)
  3428. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3429. self.ui.toolbarview.setObjectName('View_TB')
  3430. self.ui.addToolBar(self.ui.toolbarview)
  3431. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3432. self.ui.toolbarshell.setObjectName('Shell_TB')
  3433. self.ui.addToolBar(self.ui.toolbarshell)
  3434. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3435. self.ui.toolbartools.setObjectName('Tools_TB')
  3436. self.ui.addToolBar(self.ui.toolbartools)
  3437. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3438. self.ui.exc_edit_toolbar.setVisible(False)
  3439. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3440. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3441. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3442. self.ui.geo_edit_toolbar.setVisible(False)
  3443. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3444. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3445. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3446. self.ui.grb_edit_toolbar.setVisible(False)
  3447. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3448. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3449. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3450. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3451. # self.ui.snap_toolbar.setMaximumHeight(30)
  3452. self.ui.addToolBar(self.ui.snap_toolbar)
  3453. self.ui.corner_snap_btn.setVisible(False)
  3454. self.ui.snap_magnet.setVisible(False)
  3455. elif current_layout == 'compact':
  3456. ### TOOLBAR INSTALLATION ###
  3457. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3458. self.ui.toolbarfile.setObjectName('File_TB')
  3459. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3460. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3461. self.ui.toolbargeo.setObjectName('Edit_TB')
  3462. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3463. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3464. self.ui.toolbarview.setObjectName('View_TB')
  3465. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3466. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3467. self.ui.toolbarshell.setObjectName('Shell_TB')
  3468. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3469. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3470. self.ui.toolbartools.setObjectName('Tools_TB')
  3471. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3472. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3473. # self.ui.geo_edit_toolbar.setVisible(False)
  3474. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3475. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3476. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3477. # self.ui.grb_edit_toolbar.setVisible(False)
  3478. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3479. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3480. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3481. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3482. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3483. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3484. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3485. self.ui.snap_toolbar.setMaximumHeight(30)
  3486. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3487. self.ui.corner_snap_btn.setVisible(True)
  3488. self.ui.snap_magnet.setVisible(True)
  3489. # add all the actions to the toolbars
  3490. self.ui.populate_toolbars()
  3491. # reconnect all the signals to the toolbar actions
  3492. self.connect_toolbar_signals()
  3493. self.ui.grid_snap_btn.setChecked(True)
  3494. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3495. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3496. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3497. self.ui.grid_gap_link_cb.setChecked(True)
  3498. def on_cnc_custom_parameters(self, signal_text):
  3499. if signal_text == 'Parameters':
  3500. return
  3501. else:
  3502. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3503. def on_save_button(self):
  3504. self.save_defaults(silent=False)
  3505. # load the defaults so they are updated into the app
  3506. self.load_defaults(filename='current_defaults')
  3507. # Re-fresh project options
  3508. self.on_options_app2project()
  3509. def handlePrint(self):
  3510. self.report_usage("handlePrint()")
  3511. dialog = QtPrintSupport.QPrintDialog()
  3512. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3513. self.ui.code_editor.document().print_(dialog.printer())
  3514. def handlePreview(self):
  3515. self.report_usage("handlePreview()")
  3516. dialog = QtPrintSupport.QPrintPreviewDialog()
  3517. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3518. dialog.exec_()
  3519. def handleTextChanged(self):
  3520. # enable = not self.ui.code_editor.document().isEmpty()
  3521. # self.ui.buttonPrint.setEnabled(enable)
  3522. # self.ui.buttonPreview.setEnabled(enable)
  3523. pass
  3524. def handleOpen(self, filt=None):
  3525. self.report_usage("handleOpen()")
  3526. if filt:
  3527. _filter_ = filt
  3528. else:
  3529. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3530. "All Files (*.*)"
  3531. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3532. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3533. if path:
  3534. file = QtCore.QFile(path)
  3535. if file.open(QtCore.QIODevice.ReadOnly):
  3536. stream = QtCore.QTextStream(file)
  3537. self.gcode_edited = stream.readAll()
  3538. self.ui.code_editor.setPlainText(self.gcode_edited)
  3539. file.close()
  3540. def handleSaveGCode(self,name=None, filt=None):
  3541. self.report_usage("handleSaveGCode()")
  3542. if filt:
  3543. _filter_ = filt
  3544. else:
  3545. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3546. "All Files (*.*)"
  3547. if name:
  3548. obj_name = name
  3549. else:
  3550. try:
  3551. obj_name = self.collection.get_active().options['name']
  3552. except AttributeError:
  3553. obj_name = 'file'
  3554. if filt is None:
  3555. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3556. try:
  3557. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3558. caption=_("Export G-Code ..."),
  3559. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3560. filter=_filter_
  3561. )[0])
  3562. except TypeError:
  3563. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3564. if filename == "":
  3565. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  3566. return
  3567. else:
  3568. try:
  3569. my_gcode = self.ui.code_editor.toPlainText()
  3570. with open(filename, 'w') as f:
  3571. for line in my_gcode:
  3572. f.write(line)
  3573. except FileNotFoundError:
  3574. self.inform.emit(_("[WARNING] No such file or directory"))
  3575. return
  3576. # Just for adding it to the recent files list.
  3577. self.file_opened.emit("cncjob", filename)
  3578. self.file_saved.emit("cncjob", filename)
  3579. self.inform.emit(_("Saved to: %s") % filename)
  3580. def handleFindGCode(self):
  3581. self.report_usage("handleFindGCode()")
  3582. flags = QtGui.QTextDocument.FindCaseSensitively
  3583. text_to_be_found = self.ui.entryFind.get_value()
  3584. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3585. if r is False:
  3586. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3587. def handleReplaceGCode(self):
  3588. self.report_usage("handleReplaceGCode()")
  3589. old = self.ui.entryFind.get_value()
  3590. new = self.ui.entryReplace.get_value()
  3591. if self.ui.sel_all_cb.isChecked():
  3592. while True:
  3593. cursor = self.ui.code_editor.textCursor()
  3594. cursor.beginEditBlock()
  3595. flags = QtGui.QTextDocument.FindCaseSensitively
  3596. # self.ui.editor is the QPlainTextEdit
  3597. r = self.ui.code_editor.find(str(old), flags)
  3598. if r:
  3599. qc = self.ui.code_editor.textCursor()
  3600. if qc.hasSelection():
  3601. qc.insertText(new)
  3602. else:
  3603. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3604. break
  3605. # Mark end of undo block
  3606. cursor.endEditBlock()
  3607. else:
  3608. cursor = self.ui.code_editor.textCursor()
  3609. cursor.beginEditBlock()
  3610. qc = self.ui.code_editor.textCursor()
  3611. if qc.hasSelection():
  3612. qc.insertText(new)
  3613. # Mark end of undo block
  3614. cursor.endEditBlock()
  3615. def on_tool_add_keypress(self):
  3616. ## Current application units in Upper Case
  3617. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3618. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3619. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3620. if notebook_widget_name == 'selected_tab':
  3621. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3622. # Tool add works for Geometry only if Advanced is True in Preferences
  3623. if self.defaults["global_app_level"] == 'a':
  3624. tool_add_popup = FCInputDialog(title="New Tool ...",
  3625. text='Enter a Tool Diameter:',
  3626. min=0.0000, max=99.9999, decimals=4)
  3627. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3628. val, ok = tool_add_popup.get_value()
  3629. if ok:
  3630. if float(val) == 0:
  3631. self.inform.emit(
  3632. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3633. return
  3634. self.collection.get_active().on_tool_add(dia=float(val))
  3635. else:
  3636. self.inform.emit(
  3637. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3638. else:
  3639. msgbox = QtWidgets.QMessageBox()
  3640. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3641. "Go to Preferences -> General - Show Advanced Options."))
  3642. msgbox.setWindowTitle("Tool adding ...")
  3643. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3644. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3645. msgbox.setDefaultButton(bt_ok)
  3646. msgbox.exec_()
  3647. # work only if the notebook tab on focus is the Tools_Tab
  3648. if notebook_widget_name == 'tool_tab':
  3649. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3650. tool_add_popup = FCInputDialog(title="New Tool ...",
  3651. text='Enter a Tool Diameter:',
  3652. min=0.0000, max=99.9999, decimals=4)
  3653. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3654. val, ok = tool_add_popup.get_value()
  3655. # and only if the tool is NCC Tool
  3656. if tool_widget == self.ncclear_tool.toolName:
  3657. if ok:
  3658. if float(val) == 0:
  3659. self.inform.emit(
  3660. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3661. return
  3662. self.ncclear_tool.on_tool_add(dia=float(val))
  3663. else:
  3664. self.inform.emit(
  3665. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3666. # and only if the tool is Paint Area Tool
  3667. elif tool_widget == self.paint_tool.toolName:
  3668. if ok:
  3669. if float(val) == 0:
  3670. self.inform.emit(
  3671. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3672. return
  3673. self.paint_tool.on_tool_add(dia=float(val))
  3674. else:
  3675. self.inform.emit(
  3676. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3677. # and only if the tool is Solder Paste Dispensing Tool
  3678. elif tool_widget == self.paste_tool.toolName:
  3679. if ok:
  3680. if float(val) == 0:
  3681. self.inform.emit(
  3682. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3683. return
  3684. self.paste_tool.on_tool_add(dia=float(val))
  3685. else:
  3686. self.inform.emit(
  3687. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3688. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3689. # See description bellow.
  3690. def on_delete_keypress(self):
  3691. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3692. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3693. if notebook_widget_name == 'selected_tab':
  3694. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3695. self.collection.get_active().on_tool_delete()
  3696. # work only if the notebook tab on focus is the Tools_Tab
  3697. elif notebook_widget_name == 'tool_tab':
  3698. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3699. # and only if the tool is NCC Tool
  3700. if tool_widget == self.ncclear_tool.toolName:
  3701. self.ncclear_tool.on_tool_delete()
  3702. # and only if the tool is Paint Tool
  3703. elif tool_widget == self.paint_tool.toolName:
  3704. self.paint_tool.on_tool_delete()
  3705. # and only if the tool is Solder Paste Dispensing Tool
  3706. elif tool_widget == self.paste_tool.toolName:
  3707. self.paste_tool.on_tool_delete()
  3708. else:
  3709. self.on_delete()
  3710. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3711. # some screens you have to be careful where you hover with your mouse.
  3712. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3713. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3714. # Complicated, I know :)
  3715. def on_delete(self):
  3716. """
  3717. Delete the currently selected FlatCAMObjs.
  3718. :return: None
  3719. """
  3720. self.report_usage("on_delete()")
  3721. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3722. # a geometry object before we update it.
  3723. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3724. if self.collection.get_active():
  3725. self.log.debug("on_delete()")
  3726. self.report_usage("on_delete")
  3727. while (self.collection.get_active()):
  3728. self.delete_first_selected()
  3729. self.inform.emit(_("Object(s) deleted ..."))
  3730. # make sure that the selection shape is deleted, too
  3731. self.delete_selection_shape()
  3732. else:
  3733. self.inform.emit(_("Failed. No object(s) selected..."))
  3734. else:
  3735. self.inform.emit(_("Save the work in Editor and try again ..."))
  3736. def on_set_origin(self):
  3737. """
  3738. Set the origin to the left mouse click position
  3739. :return: None
  3740. """
  3741. #display the message for the user
  3742. #and ask him to click on the desired position
  3743. self.report_usage("on_set_origin()")
  3744. self.inform.emit(_('Click to set the origin ...'))
  3745. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3746. def on_jump_to(self, custom_location=None, fit_center=True):
  3747. """
  3748. Jump to a location by setting the mouse cursor location
  3749. :return:
  3750. """
  3751. self.report_usage("on_jump_to()")
  3752. if custom_location is None:
  3753. dia_box = Dialog_box(title=_("Jump to ..."),
  3754. label=_("Enter the coordinates in format X,Y:"),
  3755. icon=QtGui.QIcon('share/jump_to16.png'))
  3756. if dia_box.ok is True:
  3757. try:
  3758. location = eval(dia_box.location)
  3759. if not isinstance(location, tuple):
  3760. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3761. return
  3762. except:
  3763. return
  3764. else:
  3765. return
  3766. else:
  3767. location = custom_location
  3768. if fit_center:
  3769. self.plotcanvas.fit_center(loc=location)
  3770. cursor = QtGui.QCursor()
  3771. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3772. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3773. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3774. self.inform.emit(_("[success] Done."))
  3775. def on_copy_object(self):
  3776. self.report_usage("on_copy_object()")
  3777. def initialize(obj_init, app):
  3778. obj_init.solid_geometry = obj.solid_geometry
  3779. try:
  3780. obj_init.follow_geometry = obj.follow_geometry
  3781. except:
  3782. pass
  3783. try:
  3784. obj_init.apertures = obj.apertures
  3785. except:
  3786. pass
  3787. try:
  3788. if obj.tools:
  3789. obj_init.tools = obj.tools
  3790. except Exception as e:
  3791. log.debug("on_copy_object() --> %s" % str(e))
  3792. def initialize_excellon(obj_init, app):
  3793. obj_init.tools = obj.tools
  3794. # drills are offset, so they need to be deep copied
  3795. obj_init.drills = deepcopy(obj.drills)
  3796. # slots are offset, so they need to be deep copied
  3797. obj_init.slots = deepcopy(obj.slots)
  3798. obj_init.create_geometry()
  3799. for obj in self.collection.get_selected():
  3800. obj_name = obj.options["name"]
  3801. try:
  3802. if isinstance(obj, FlatCAMExcellon):
  3803. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3804. elif isinstance(obj,FlatCAMGerber):
  3805. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3806. elif isinstance(obj,FlatCAMGeometry):
  3807. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3808. except Exception as e:
  3809. return "Operation failed: %s" % str(e)
  3810. def on_copy_object2(self, custom_name):
  3811. def initialize_geometry(obj_init, app):
  3812. obj_init.solid_geometry = obj.solid_geometry
  3813. try:
  3814. obj_init.follow_geometry = obj.follow_geometry
  3815. except:
  3816. pass
  3817. try:
  3818. obj_init.apertures = obj.apertures
  3819. except:
  3820. pass
  3821. try:
  3822. if obj.tools:
  3823. obj_init.tools = obj.tools
  3824. except Exception as e:
  3825. log.debug("on_copy_object2() --> %s" % str(e))
  3826. def initialize_gerber(obj_init, app):
  3827. obj_init.solid_geometry = obj.solid_geometry
  3828. obj_init.apertures = deepcopy(obj.apertures)
  3829. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3830. def initialize_excellon(obj_init, app):
  3831. obj_init.tools = obj.tools
  3832. # drills are offset, so they need to be deep copied
  3833. obj_init.drills = deepcopy(obj.drills)
  3834. # slots are offset, so they need to be deep copied
  3835. obj_init.slots = deepcopy(obj.slots)
  3836. obj_init.create_geometry()
  3837. for obj in self.collection.get_selected():
  3838. obj_name = obj.options["name"]
  3839. try:
  3840. if isinstance(obj, FlatCAMExcellon):
  3841. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3842. elif isinstance(obj,FlatCAMGerber):
  3843. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3844. elif isinstance(obj,FlatCAMGeometry):
  3845. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3846. except Exception as e:
  3847. return "Operation failed: %s" % str(e)
  3848. def on_rename_object(self, text):
  3849. self.report_usage("on_rename_object()")
  3850. named_obj = self.collection.get_active()
  3851. for obj in named_obj:
  3852. if obj is list:
  3853. self.on_rename_object(text)
  3854. else:
  3855. try:
  3856. obj.options['name'] = text
  3857. except:
  3858. log.warning("Could not rename the object in the list")
  3859. def on_copy_object_as_geometry(self):
  3860. self.report_usage("on_copy_object_as_geometry()")
  3861. def initialize(obj_init, app):
  3862. obj_init.solid_geometry = obj.solid_geometry
  3863. try:
  3864. obj_init.follow_geometry = obj.follow_geometry
  3865. except:
  3866. pass
  3867. try:
  3868. obj_init.apertures = obj.apertures
  3869. except:
  3870. pass
  3871. if obj.tools:
  3872. obj_init.tools = obj.tools
  3873. def initialize_excellon(obj_init, app):
  3874. # objs = self.collection.get_selected()
  3875. # FlatCAMGeometry.merge(objs, obj)
  3876. solid_geo = []
  3877. for tool in obj.tools:
  3878. for geo in obj.tools[tool]['solid_geometry']:
  3879. solid_geo.append(geo)
  3880. obj_init.solid_geometry = deepcopy(solid_geo)
  3881. for obj in self.collection.get_selected():
  3882. obj_name = obj.options["name"]
  3883. try:
  3884. if isinstance(obj, FlatCAMExcellon):
  3885. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3886. else:
  3887. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3888. except Exception as e:
  3889. return "Operation failed: %s" % str(e)
  3890. def on_set_zero_click(self, event):
  3891. #this function will be available only for mouse left click
  3892. pos =[]
  3893. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3894. if event.button == 1:
  3895. if self.grid_status() == True:
  3896. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3897. else:
  3898. pos = pos_canvas
  3899. x = 0 - pos[0]
  3900. y = 0 - pos[1]
  3901. for obj in self.collection.get_list():
  3902. obj.offset((x,y))
  3903. self.object_changed.emit(obj)
  3904. obj.plot()
  3905. # Update the object bounding box options
  3906. a, b, c, d = obj.bounds()
  3907. obj.options['xmin'] = a
  3908. obj.options['ymin'] = b
  3909. obj.options['xmax'] = c
  3910. obj.options['ymax'] = d
  3911. # self.plot_all(zoom=False)
  3912. self.inform.emit(_('[success] Origin set ...'))
  3913. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3914. self.should_we_save = True
  3915. def on_selectall(self):
  3916. self.report_usage("on_selectall()")
  3917. # delete the possible selection box around a possible selected object
  3918. self.delete_selection_shape()
  3919. for name in self.collection.get_names():
  3920. self.collection.set_active(name)
  3921. curr_sel_obj = self.collection.get_by_name(name)
  3922. # create the selection box around the selected object
  3923. if self.defaults['global_selection_shape'] is True:
  3924. self.draw_selection_shape(curr_sel_obj)
  3925. def on_preferences(self):
  3926. # add the tab if it was closed
  3927. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  3928. # delete the absolute and relative position and messages in the infobar
  3929. self.ui.position_label.setText("")
  3930. self.ui.rel_position_label.setText("")
  3931. # Switch plot_area to preferences page
  3932. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3933. self.ui.show()
  3934. def on_flipy(self):
  3935. self.report_usage("on_flipy()")
  3936. obj_list = self.collection.get_selected()
  3937. xminlist = []
  3938. yminlist = []
  3939. xmaxlist = []
  3940. ymaxlist = []
  3941. if not obj_list:
  3942. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  3943. else:
  3944. try:
  3945. # first get a bounding box to fit all
  3946. for obj in obj_list:
  3947. xmin, ymin, xmax, ymax = obj.bounds()
  3948. xminlist.append(xmin)
  3949. yminlist.append(ymin)
  3950. xmaxlist.append(xmax)
  3951. ymaxlist.append(ymax)
  3952. # get the minimum x,y and maximum x,y for all objects selected
  3953. xminimal = min(xminlist)
  3954. yminimal = min(yminlist)
  3955. xmaximal = max(xmaxlist)
  3956. ymaximal = max(ymaxlist)
  3957. px = 0.5 * (xminimal + xmaximal)
  3958. py = 0.5 * (yminimal + ymaximal)
  3959. # execute mirroring
  3960. for obj in obj_list:
  3961. obj.mirror('X', [px, py])
  3962. obj.plot()
  3963. self.object_changed.emit(obj)
  3964. self.inform.emit(_("[success] Flip on Y axis done."))
  3965. except Exception as e:
  3966. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3967. return
  3968. def on_flipx(self):
  3969. self.report_usage("on_flipx()")
  3970. obj_list = self.collection.get_selected()
  3971. xminlist = []
  3972. yminlist = []
  3973. xmaxlist = []
  3974. ymaxlist = []
  3975. if not obj_list:
  3976. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  3977. else:
  3978. try:
  3979. # first get a bounding box to fit all
  3980. for obj in obj_list:
  3981. xmin, ymin, xmax, ymax = obj.bounds()
  3982. xminlist.append(xmin)
  3983. yminlist.append(ymin)
  3984. xmaxlist.append(xmax)
  3985. ymaxlist.append(ymax)
  3986. # get the minimum x,y and maximum x,y for all objects selected
  3987. xminimal = min(xminlist)
  3988. yminimal = min(yminlist)
  3989. xmaximal = max(xmaxlist)
  3990. ymaximal = max(ymaxlist)
  3991. px = 0.5 * (xminimal + xmaximal)
  3992. py = 0.5 * (yminimal + ymaximal)
  3993. # execute mirroring
  3994. for obj in obj_list:
  3995. obj.mirror('Y', [px, py])
  3996. obj.plot()
  3997. self.object_changed.emit(obj)
  3998. self.inform.emit(_("[success] Flip on X axis done."))
  3999. except Exception as e:
  4000. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  4001. return
  4002. def on_rotate(self, silent=False, preset=None):
  4003. self.report_usage("on_rotate()")
  4004. obj_list = self.collection.get_selected()
  4005. xminlist = []
  4006. yminlist = []
  4007. xmaxlist = []
  4008. ymaxlist = []
  4009. if not obj_list:
  4010. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  4011. else:
  4012. if silent is False:
  4013. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4014. min=-360, max=360, decimals=4,
  4015. init_val=float(self.defaults['tools_transform_rotate']))
  4016. num, ok = rotatebox.get_value()
  4017. else:
  4018. num = preset
  4019. ok = True
  4020. if ok:
  4021. try:
  4022. # first get a bounding box to fit all
  4023. for obj in obj_list:
  4024. xmin, ymin, xmax, ymax = obj.bounds()
  4025. xminlist.append(xmin)
  4026. yminlist.append(ymin)
  4027. xmaxlist.append(xmax)
  4028. ymaxlist.append(ymax)
  4029. # get the minimum x,y and maximum x,y for all objects selected
  4030. xminimal = min(xminlist)
  4031. yminimal = min(yminlist)
  4032. xmaximal = max(xmaxlist)
  4033. ymaximal = max(ymaxlist)
  4034. px = 0.5 * (xminimal + xmaximal)
  4035. py = 0.5 * (yminimal + ymaximal)
  4036. for sel_obj in obj_list:
  4037. sel_obj.rotate(-float(num), point=(px, py))
  4038. sel_obj.plot()
  4039. self.object_changed.emit(sel_obj)
  4040. self.inform.emit(_("[success] Rotation done."))
  4041. except Exception as e:
  4042. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  4043. return
  4044. def on_skewx(self):
  4045. self.report_usage("on_skewx()")
  4046. obj_list = self.collection.get_selected()
  4047. xminlist = []
  4048. yminlist = []
  4049. if not obj_list:
  4050. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  4051. else:
  4052. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4053. min=-360, max=360, decimals=4,
  4054. init_val=float(self.defaults['tools_transform_skew_x']))
  4055. num, ok = skewxbox.get_value()
  4056. if ok:
  4057. # first get a bounding box to fit all
  4058. for obj in obj_list:
  4059. xmin, ymin, xmax, ymax = obj.bounds()
  4060. xminlist.append(xmin)
  4061. yminlist.append(ymin)
  4062. # get the minimum x,y and maximum x,y for all objects selected
  4063. xminimal = min(xminlist)
  4064. yminimal = min(yminlist)
  4065. for obj in obj_list:
  4066. obj.skew(num, 0, point=(xminimal, yminimal))
  4067. obj.plot()
  4068. self.object_changed.emit(obj)
  4069. self.inform.emit(_("[success] Skew on X axis done."))
  4070. def on_skewy(self):
  4071. self.report_usage("on_skewy()")
  4072. obj_list = self.collection.get_selected()
  4073. xminlist = []
  4074. yminlist = []
  4075. if not obj_list:
  4076. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  4077. else:
  4078. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4079. min=-360, max=360, decimals=4,
  4080. init_val=float(self.defaults['tools_transform_skew_y']))
  4081. num, ok = skewybox.get_value()
  4082. if ok:
  4083. # first get a bounding box to fit all
  4084. for obj in obj_list:
  4085. xmin, ymin, xmax, ymax = obj.bounds()
  4086. xminlist.append(xmin)
  4087. yminlist.append(ymin)
  4088. # get the minimum x,y and maximum x,y for all objects selected
  4089. xminimal = min(xminlist)
  4090. yminimal = min(yminlist)
  4091. for obj in obj_list:
  4092. obj.skew(0, num, point=(xminimal, yminimal))
  4093. obj.plot()
  4094. self.object_changed.emit(obj)
  4095. self.inform.emit(_("[success] Skew on Y axis done."))
  4096. def delete_first_selected(self):
  4097. # Keep this for later
  4098. try:
  4099. name = self.collection.get_active().options["name"]
  4100. except AttributeError:
  4101. self.log.debug("Nothing selected for deletion")
  4102. return
  4103. # Remove plot
  4104. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4105. # self.plotcanvas.auto_adjust_axes()
  4106. # Clear form
  4107. self.setup_component_editor()
  4108. # Remove from dictionary
  4109. self.collection.delete_active()
  4110. self.inform.emit("Object deleted: %s" % name)
  4111. def on_plots_updated(self):
  4112. """
  4113. Callback used to report when the plots have changed.
  4114. Adjust axes and zooms to fit.
  4115. :return: None
  4116. """
  4117. # self.plotcanvas.auto_adjust_axes()
  4118. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  4119. self.on_zoom_fit(None)
  4120. # TODO: Rework toolbar 'clear', 'replot' functions
  4121. def on_toolbar_replot(self):
  4122. """
  4123. Callback for toolbar button. Re-plots all objects.
  4124. :return: None
  4125. """
  4126. self.report_usage("on_toolbar_replot")
  4127. self.log.debug("on_toolbar_replot()")
  4128. try:
  4129. self.collection.get_active().read_form()
  4130. except AttributeError:
  4131. self.log.debug("on_toolbar_replot(): AttributeError")
  4132. pass
  4133. self.plot_all()
  4134. def on_row_activated(self, index):
  4135. if index.isValid():
  4136. if index.internalPointer().parent_item != self.collection.root_item:
  4137. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4138. def grid_status(self):
  4139. if self.ui.grid_snap_btn.isChecked():
  4140. return 1
  4141. else:
  4142. return 0
  4143. def populate_cmenu_grids(self):
  4144. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4145. self.ui.cmenu_gridmenu.clear()
  4146. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4147. for grid in sorted_list:
  4148. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4149. action.triggered.connect(self.set_grid)
  4150. self.ui.cmenu_gridmenu.addSeparator()
  4151. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  4152. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  4153. grid_add.triggered.connect(self.on_grid_add)
  4154. grid_delete.triggered.connect(self.on_grid_delete)
  4155. def set_grid(self):
  4156. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4157. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4158. def on_grid_add(self):
  4159. ## Current application units in lower Case
  4160. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4161. grid_add_popup = FCInputDialog(title="New Grid ...",
  4162. text='Enter a Grid VAlue:',
  4163. min=0.0000, max=99.9999, decimals=4)
  4164. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4165. val, ok = grid_add_popup.get_value()
  4166. if ok:
  4167. if float(val) == 0:
  4168. self.inform.emit(
  4169. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4170. return
  4171. else:
  4172. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4173. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4174. self.inform.emit(
  4175. _("[success] New Grid added ..."))
  4176. else:
  4177. self.inform.emit(
  4178. _("[WARNING_NOTCL] Grid already exists ..."))
  4179. else:
  4180. self.inform.emit(
  4181. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4182. def on_grid_delete(self):
  4183. ## Current application units in lower Case
  4184. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4185. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4186. text='Enter a Grid Value:',
  4187. min=0.0000, max=99.9999, decimals=4)
  4188. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4189. val, ok = grid_del_popup.get_value()
  4190. if ok:
  4191. if float(val) == 0:
  4192. self.inform.emit(
  4193. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4194. return
  4195. else:
  4196. try:
  4197. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4198. except ValueError:
  4199. self.inform.emit(
  4200. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4201. return
  4202. self.inform.emit(
  4203. _("[success] Grid Value deleted ..."))
  4204. else:
  4205. self.inform.emit(
  4206. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4207. def on_shortcut_list(self):
  4208. self.report_usage("on_shortcut_list()")
  4209. # add the tab if it was closed
  4210. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  4211. # delete the absolute and relative position and messages in the infobar
  4212. self.ui.position_label.setText("")
  4213. self.ui.rel_position_label.setText("")
  4214. # Switch plot_area to preferences page
  4215. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4216. self.ui.show()
  4217. def on_select_tab(self, name):
  4218. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4219. if self.ui.splitter.sizes()[0] == 0:
  4220. self.ui.splitter.setSizes([1, 1])
  4221. else:
  4222. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4223. self.ui.splitter.setSizes([0, 1])
  4224. if name == 'project':
  4225. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4226. elif name == 'selected':
  4227. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4228. elif name == 'tool':
  4229. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4230. def on_copy_name(self):
  4231. self.report_usage("on_copy_name()")
  4232. obj = self.collection.get_active()
  4233. try:
  4234. name = obj.options["name"]
  4235. except AttributeError:
  4236. log.debug("on_copy_name() --> No object selected to copy it's name")
  4237. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4238. return
  4239. self.clipboard.setText(name)
  4240. self.inform.emit(_("Name copied on clipboard ..."))
  4241. def on_mouse_click_over_plot(self, event):
  4242. """
  4243. Default actions are:
  4244. :param event: Contains information about the event, like which button
  4245. was clicked, the pixel coordinates and the axes coordinates.
  4246. :return: None
  4247. """
  4248. self.pos = []
  4249. # So it can receive key presses
  4250. self.plotcanvas.vispy_canvas.native.setFocus()
  4251. # Set the mouse button for panning
  4252. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4253. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4254. if self.grid_status() == True:
  4255. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4256. self.app_cursor.enabled = True
  4257. else:
  4258. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4259. self.app_cursor.enabled = False
  4260. try:
  4261. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4262. if event.button == 1:
  4263. # Reset here the relative coordinates so there is a new reference on the click position
  4264. if self.rel_point1 is None:
  4265. self.rel_point1 = self.pos
  4266. else:
  4267. self.rel_point2 = copy(self.rel_point1)
  4268. self.rel_point1 = self.pos
  4269. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4270. if modifiers == QtCore.Qt.ShiftModifier:
  4271. # do not auto open the Project Tab
  4272. self.click_noproject = True
  4273. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4274. return
  4275. self.on_mouse_move_over_plot(event, origin_click=True)
  4276. except Exception as e:
  4277. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4278. def on_double_click_over_plot(self, event):
  4279. self.doubleclick = True
  4280. def on_mouse_move_over_plot(self, event, origin_click=None):
  4281. """
  4282. Callback for the mouse motion event over the plot.
  4283. :param event: Contains information about the event.
  4284. :param origin_click
  4285. :return: None
  4286. """
  4287. # So it can receive key presses
  4288. self.plotcanvas.vispy_canvas.native.setFocus()
  4289. self.pos_jump = event.pos
  4290. self.ui.popMenu.mouse_is_panning = False
  4291. if origin_click != True:
  4292. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4293. if event.button == 2 and event.is_dragging == 1:
  4294. self.ui.popMenu.mouse_is_panning = True
  4295. return
  4296. if self.rel_point1 is not None:
  4297. try: # May fail in case mouse not within axes
  4298. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4299. if self.grid_status():
  4300. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4301. self.app_cursor.enabled = True
  4302. # Update cursor
  4303. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4304. else:
  4305. pos = (pos_canvas[0], pos_canvas[1])
  4306. self.app_cursor.enabled = False
  4307. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4308. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4309. dx = pos[0] - self.rel_point1[0]
  4310. dy = pos[1] - self.rel_point1[1]
  4311. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4312. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4313. self.mouse = [pos[0], pos[1]]
  4314. # if the mouse is moved and the LMB is clicked then the action is a selection
  4315. if event.is_dragging == 1 and event.button == 1:
  4316. self.delete_selection_shape()
  4317. if dx < 0:
  4318. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4319. face_color=self.defaults['global_alt_sel_fill'])
  4320. self.selection_type = False
  4321. else:
  4322. self.draw_moving_selection_shape(self.pos, pos)
  4323. self.selection_type = True
  4324. # hover effect - enabled in Preferences -> General -> GUI Settings
  4325. if self.defaults['global_hover']:
  4326. for obj in self.collection.get_list():
  4327. try:
  4328. # select the object(s) only if it is enabled (plotted)
  4329. if obj.options['plot']:
  4330. if obj not in self.collection.get_selected():
  4331. poly_obj = Polygon(
  4332. [(obj.options['xmin'], obj.options['ymin']),
  4333. (obj.options['xmax'], obj.options['ymin']),
  4334. (obj.options['xmax'], obj.options['ymax']),
  4335. (obj.options['xmin'], obj.options['ymax'])]
  4336. )
  4337. if Point(pos).within(poly_obj):
  4338. if obj.isHovering is False:
  4339. obj.isHovering = True
  4340. obj.notHovering = True
  4341. # create the selection box around the selected object
  4342. self.draw_hover_shape(obj, color='#d1e0e0')
  4343. else:
  4344. if obj.notHovering is True:
  4345. obj.notHovering = False
  4346. obj.isHovering = False
  4347. self.delete_hover_shape()
  4348. except:
  4349. # the Exception here will happen if we try to select on screen and we have an
  4350. # newly (and empty) just created Geometry or Excellon object that do not have the
  4351. # xmin, xmax, ymin, ymax options.
  4352. # In this case poly_obj creation (see above) will fail
  4353. pass
  4354. except:
  4355. self.ui.position_label.setText("")
  4356. self.ui.rel_position_label.setText("")
  4357. self.mouse = None
  4358. def on_mouse_click_release_over_plot(self, event):
  4359. """
  4360. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4361. and has been registered in ''self.__init__()''.
  4362. :param event: contains information about the event.
  4363. :return:
  4364. """
  4365. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4366. if self.grid_status():
  4367. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4368. else:
  4369. pos = (pos_canvas[0], pos_canvas[1])
  4370. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4371. # canvas menu
  4372. try:
  4373. if event.button == 2: # right click
  4374. if self.ui.popMenu.mouse_is_panning is False:
  4375. self.cursor = QtGui.QCursor()
  4376. self.populate_cmenu_grids()
  4377. self.ui.popMenu.popup(self.cursor.pos())
  4378. except Exception as e:
  4379. log.warning("Error: %s" % str(e))
  4380. return
  4381. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4382. # selection and then select a type of selection ("enclosing" or "touching")
  4383. try:
  4384. if event.button == 1: # left click
  4385. if self.doubleclick is True:
  4386. self.doubleclick = False
  4387. if self.collection.get_selected():
  4388. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4389. if self.ui.splitter.sizes()[0] == 0:
  4390. self.ui.splitter.setSizes([1, 1])
  4391. # delete the selection shape(S) as it may be in the way
  4392. self.delete_selection_shape()
  4393. self.delete_hover_shape()
  4394. else:
  4395. if self.selection_type is not None:
  4396. self.selection_area_handler(self.pos, pos, self.selection_type)
  4397. self.selection_type = None
  4398. else:
  4399. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4400. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  4401. # and if it's not selected then it will be selected
  4402. if modifiers == QtCore.Qt.ControlModifier:
  4403. # If there is no active command (self.command_active is None) then we check if we clicked on
  4404. # a object by checking the bounding limits against mouse click position
  4405. if self.command_active is None:
  4406. self.select_objects(key='CTRL')
  4407. self.delete_hover_shape()
  4408. else:
  4409. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  4410. # checking the bounding limits against mouse click position
  4411. if self.command_active is None:
  4412. self.select_objects()
  4413. self.delete_hover_shape()
  4414. except Exception as e:
  4415. log.warning("Error: %s" % str(e))
  4416. return
  4417. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4418. """
  4419. :param start_pos: mouse position when the selection LMB click was done
  4420. :param end_pos: mouse position when the left mouse button is released
  4421. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4422. :return:
  4423. """
  4424. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4425. self.delete_selection_shape()
  4426. for obj in self.collection.get_list():
  4427. try:
  4428. # select the object(s) only if it is enabled (plotted)
  4429. if obj.options['plot']:
  4430. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4431. (obj.options['xmax'], obj.options['ymin']),
  4432. (obj.options['xmax'], obj.options['ymax']),
  4433. (obj.options['xmin'], obj.options['ymax'])])
  4434. if sel_type is True:
  4435. if poly_obj.within(poly_selection):
  4436. # create the selection box around the selected object
  4437. if self.defaults['global_selection_shape'] is True:
  4438. self.draw_selection_shape(obj)
  4439. self.collection.set_active(obj.options['name'])
  4440. else:
  4441. if poly_selection.intersects(poly_obj):
  4442. # create the selection box around the selected object
  4443. if self.defaults['global_selection_shape'] is True:
  4444. self.draw_selection_shape(obj)
  4445. self.collection.set_active(obj.options['name'])
  4446. except:
  4447. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4448. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4449. # In this case poly_obj creation (see above) will fail
  4450. pass
  4451. def select_objects(self, key=None):
  4452. # list where we store the overlapped objects under our mouse left click position
  4453. objects_under_the_click_list = []
  4454. # Populate the list with the overlapped objects on the click position
  4455. curr_x, curr_y = self.pos
  4456. for obj in self.all_objects_list:
  4457. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4458. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4459. if obj.options['name'] not in objects_under_the_click_list:
  4460. if obj.options['plot']:
  4461. # add objects to the objects_under_the_click list only if the object is plotted
  4462. # (active and not disabled)
  4463. objects_under_the_click_list.append(obj.options['name'])
  4464. try:
  4465. # If there is no element in the overlapped objects list then make everyone inactive
  4466. # because we selected "nothing"
  4467. if not objects_under_the_click_list:
  4468. self.collection.set_all_inactive()
  4469. # delete the possible selection box around a possible selected object
  4470. self.delete_selection_shape()
  4471. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4472. # only when working on App
  4473. if self.call_source == 'app':
  4474. if self.click_noproject is False:
  4475. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4476. else:
  4477. # restore auto open the Project Tab
  4478. self.click_noproject = False
  4479. # delete any text in the status bar, implicitly the last object name that was selected
  4480. self.inform.emit("")
  4481. else:
  4482. self.call_source = 'app'
  4483. else:
  4484. # case when there is only an object under the click and we toggle it
  4485. if len(objects_under_the_click_list) == 1:
  4486. if self.collection.get_active() is None :
  4487. self.collection.set_active(objects_under_the_click_list[0])
  4488. # create the selection box around the selected object
  4489. curr_sel_obj = self.collection.get_active()
  4490. if self.defaults['global_selection_shape'] is True:
  4491. self.draw_selection_shape(curr_sel_obj)
  4492. # self.inform.emit('[selected] %s: %s selected' %
  4493. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4494. if curr_sel_obj.kind == 'gerber':
  4495. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4496. color='green', name=str(curr_sel_obj.options['name'])))
  4497. elif curr_sel_obj.kind == 'excellon':
  4498. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4499. color='brown', name=str(curr_sel_obj.options['name'])))
  4500. elif curr_sel_obj.kind == 'cncjob':
  4501. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4502. color='blue', name=str(curr_sel_obj.options['name'])))
  4503. elif curr_sel_obj.kind == 'geometry':
  4504. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4505. color='red', name=str(curr_sel_obj.options['name'])))
  4506. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4507. self.collection.set_all_inactive()
  4508. self.delete_selection_shape()
  4509. self.collection.set_active(objects_under_the_click_list[0])
  4510. # create the selection box around the selected object
  4511. curr_sel_obj = self.collection.get_active()
  4512. if self.defaults['global_selection_shape'] is True:
  4513. self.draw_selection_shape(curr_sel_obj)
  4514. # self.inform.emit('[selected] %s: %s selected' %
  4515. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4516. if curr_sel_obj.kind == 'gerber':
  4517. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4518. color='green', name=str(curr_sel_obj.options['name'])))
  4519. elif curr_sel_obj.kind == 'excellon':
  4520. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4521. color='brown', name=str(curr_sel_obj.options['name'])))
  4522. elif curr_sel_obj.kind == 'cncjob':
  4523. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4524. color='blue', name=str(curr_sel_obj.options['name'])))
  4525. elif curr_sel_obj.kind == 'geometry':
  4526. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4527. color='red', name=str(curr_sel_obj.options['name'])))
  4528. else:
  4529. self.collection.set_all_inactive()
  4530. self.delete_selection_shape()
  4531. if self.call_source == 'app':
  4532. # delete any text in the status bar, implicitly the last object name that was selected
  4533. self.inform.emit("")
  4534. else:
  4535. self.call_source = 'app'
  4536. else:
  4537. # If there is no selected object
  4538. # make active the first element of the overlapped objects list
  4539. if self.collection.get_active() is None:
  4540. self.collection.set_active(objects_under_the_click_list[0])
  4541. name_sel_obj = self.collection.get_active().options['name']
  4542. # In case that there is a selected object but it is not in the overlapped object list
  4543. # make that object inactive and activate the first element in the overlapped object list
  4544. if name_sel_obj not in objects_under_the_click_list:
  4545. self.collection.set_inactive(name_sel_obj)
  4546. name_sel_obj = objects_under_the_click_list[0]
  4547. self.collection.set_active(name_sel_obj)
  4548. else:
  4549. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4550. self.collection.set_all_inactive()
  4551. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4552. len(objects_under_the_click_list)])
  4553. curr_sel_obj = self.collection.get_active()
  4554. # delete the possible selection box around a possible selected object
  4555. self.delete_selection_shape()
  4556. # create the selection box around the selected object
  4557. if self.defaults['global_selection_shape'] is True:
  4558. self.draw_selection_shape(curr_sel_obj)
  4559. # self.inform.emit('[selected] %s: %s selected' %
  4560. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4561. if curr_sel_obj.kind == 'gerber':
  4562. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4563. color='green', name=str(curr_sel_obj.options['name'])))
  4564. elif curr_sel_obj.kind == 'excellon':
  4565. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4566. color='brown', name=str(curr_sel_obj.options['name'])))
  4567. elif curr_sel_obj.kind == 'cncjob':
  4568. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4569. color='blue', name=str(curr_sel_obj.options['name'])))
  4570. elif curr_sel_obj.kind == 'geometry':
  4571. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4572. color='red', name=str(curr_sel_obj.options['name'])))
  4573. # for obj in self.collection.get_list():
  4574. # obj.plot()
  4575. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4576. # TODO: on selected objects change the object colors and do not draw the selection box
  4577. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4578. except Exception as e:
  4579. log.error("[ERROR] Something went bad. %s" % str(e))
  4580. return
  4581. def delete_hover_shape(self):
  4582. self.hover_shapes.clear()
  4583. self.hover_shapes.redraw()
  4584. def draw_hover_shape(self, sel_obj, color=None):
  4585. """
  4586. :param sel_obj: the object for which the hover shape must be drawn
  4587. :return:
  4588. """
  4589. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4590. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4591. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4592. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4593. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4594. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4595. hover_rect = hover_rect.buffer(-0.1)
  4596. hover_rect = hover_rect.buffer(0.2)
  4597. else:
  4598. hover_rect = hover_rect.buffer(-0.00393)
  4599. hover_rect = hover_rect.buffer(0.00787)
  4600. if color:
  4601. face = Color(color)
  4602. face.alpha = 0.2
  4603. outline = Color(color, alpha=0.8)
  4604. else:
  4605. face = Color(self.defaults['global_sel_fill'])
  4606. face.alpha = 0.2
  4607. outline = self.defaults['global_sel_line']
  4608. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4609. def delete_selection_shape(self):
  4610. self.move_tool.sel_shapes.clear()
  4611. self.move_tool.sel_shapes.redraw()
  4612. def draw_selection_shape(self, sel_obj, color=None):
  4613. """
  4614. :param sel_obj: the object for which the selection shape must be drawn
  4615. :return:
  4616. """
  4617. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4618. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4619. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4620. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4621. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4622. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4623. sel_rect = sel_rect.buffer(-0.1)
  4624. sel_rect = sel_rect.buffer(0.2)
  4625. else:
  4626. sel_rect = sel_rect.buffer(-0.00393)
  4627. sel_rect = sel_rect.buffer(0.00787)
  4628. if color:
  4629. face = Color(color, alpha=0.2)
  4630. outline = Color(color, alpha=0.8)
  4631. else:
  4632. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4633. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4634. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4635. face_color=face, update=True, layer=0, tolerance=None))
  4636. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4637. """
  4638. :param old_coords: old coordinates
  4639. :param coords: new coordinates
  4640. :return:
  4641. """
  4642. if 'color' in kwargs:
  4643. color = kwargs['color']
  4644. else:
  4645. color = self.defaults['global_sel_line']
  4646. if 'face_color' in kwargs:
  4647. face_color = kwargs['face_color']
  4648. else:
  4649. face_color = self.defaults['global_sel_fill']
  4650. x0, y0 = old_coords
  4651. x1, y1 = coords
  4652. pt1 = (x0, y0)
  4653. pt2 = (x1, y0)
  4654. pt3 = (x1, y1)
  4655. pt4 = (x0, y1)
  4656. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4657. color_t = Color(face_color)
  4658. color_t.alpha = 0.3
  4659. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4660. layer=0, tolerance=None)
  4661. def on_file_new_click(self):
  4662. if self.collection.get_list() and self.should_we_save:
  4663. msgbox = QtWidgets.QMessageBox()
  4664. # msgbox.setText("<B>Save changes ...</B>")
  4665. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4666. "Creating a New project will delete them.\n"
  4667. "Do you want to Save the project?"))
  4668. msgbox.setWindowTitle(_("Save changes"))
  4669. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4670. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4671. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4672. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4673. msgbox.setDefaultButton(bt_yes)
  4674. msgbox.exec_()
  4675. response = msgbox.clickedButton()
  4676. if response == bt_yes:
  4677. self.on_file_saveprojectas()
  4678. elif response == bt_cancel:
  4679. return
  4680. elif response == bt_no:
  4681. self.on_file_new()
  4682. else:
  4683. self.on_file_new()
  4684. self.inform.emit(_("[success] New Project created..."))
  4685. def on_file_new(self):
  4686. """
  4687. Callback for menu item File->New. Returns the application to its
  4688. startup state. This method is thread-safe.
  4689. :return: None
  4690. """
  4691. self.report_usage("on_file_new")
  4692. # Remove everything from memory
  4693. App.log.debug("on_file_new()")
  4694. if self.call_source != 'app':
  4695. self.editor2object(cleanup=True)
  4696. ### EDITOR section
  4697. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  4698. self.exc_editor = FlatCAMExcEditor(self)
  4699. self.grb_editor = FlatCAMGrbEditor(self)
  4700. # Clear pool
  4701. self.clear_pool()
  4702. #delete shapes left drawn from mark shape_collections, if any
  4703. for obj in self.collection.get_list():
  4704. try:
  4705. obj.mark_shapes.enabled = False
  4706. obj.mark_shapes.clear(update=True)
  4707. except:
  4708. pass
  4709. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4710. self.init_tcl()
  4711. self.delete_selection_shape()
  4712. self.collection.delete_all()
  4713. self.setup_component_editor()
  4714. # Clear project filename
  4715. self.project_filename = None
  4716. # Load the application defaults
  4717. self.load_defaults(filename='current_defaults')
  4718. # Re-fresh project options
  4719. self.on_options_app2project()
  4720. # Init Tools
  4721. self.init_tools()
  4722. # Close any Tabs opened in the Plot Tab Area section
  4723. for index in range(self.ui.plot_tab_area.count()):
  4724. self.ui.plot_tab_area.closeTab(index)
  4725. # for whatever reason previous command does not close the last tab so I do it manually
  4726. self.ui.plot_tab_area.closeTab(0)
  4727. # # And then add again the Plot Area
  4728. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4729. self.ui.plot_tab_area.protectTab(0)
  4730. # take the focus of the Notebook on Project Tab.
  4731. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4732. def obj_properties(self):
  4733. self.report_usage("obj_properties()")
  4734. self.properties_tool.run(toggle=False)
  4735. def on_project_context_save(self):
  4736. obj = self.collection.get_active()
  4737. if type(obj) == FlatCAMGeometry:
  4738. self.on_file_exportdxf()
  4739. elif type(obj) == FlatCAMExcellon:
  4740. self.on_file_saveexcellon()
  4741. elif type(obj) == FlatCAMCNCjob:
  4742. obj.on_exportgcode_button_click()
  4743. elif type(obj) == FlatCAMGerber:
  4744. self.on_file_savegerber()
  4745. def obj_move(self):
  4746. self.report_usage("obj_move()")
  4747. self.move_tool.run(toggle=False)
  4748. def on_fileopengerber(self):
  4749. """
  4750. File menu callback for opening a Gerber.
  4751. :return: None
  4752. """
  4753. self.report_usage("on_fileopengerber")
  4754. App.log.debug("on_fileopengerber()")
  4755. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4756. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4757. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  4758. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4759. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4760. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4761. "Allegro Files (*.art);;" \
  4762. "Mentor Files (*.pho *.gdo);;" \
  4763. "All Files (*.*)"
  4764. try:
  4765. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4766. directory=self.get_last_folder(), filter=_filter_)
  4767. except TypeError:
  4768. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4769. filenames = [str(filename) for filename in filenames]
  4770. if len(filenames) == 0:
  4771. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4772. else:
  4773. for filename in filenames:
  4774. if filename != '':
  4775. self.worker_task.emit({'fcn': self.open_gerber,
  4776. 'params': [filename]})
  4777. def on_fileopenexcellon(self):
  4778. """
  4779. File menu callback for opening an Excellon file.
  4780. :return: None
  4781. """
  4782. self.report_usage("on_fileopenexcellon")
  4783. App.log.debug("on_fileopenexcellon()")
  4784. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4785. "All Files (*.*)"
  4786. try:
  4787. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4788. directory=self.get_last_folder(), filter=_filter_)
  4789. except TypeError:
  4790. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4791. filenames = [str(filename) for filename in filenames]
  4792. if len(filenames) == 0:
  4793. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  4794. else:
  4795. for filename in filenames:
  4796. if filename != '':
  4797. self.worker_task.emit({'fcn': self.open_excellon,
  4798. 'params': [filename]})
  4799. def on_fileopengcode(self):
  4800. """
  4801. File menu call back for opening gcode.
  4802. :return: None
  4803. """
  4804. self.report_usage("on_fileopengcode")
  4805. App.log.debug("on_fileopengcode()")
  4806. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4807. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4808. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4809. "All Files (*.*)"
  4810. try:
  4811. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4812. directory=self.get_last_folder(), filter=_filter_)
  4813. except TypeError:
  4814. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4815. filenames = [str(filename) for filename in filenames]
  4816. if len(filenames) == 0:
  4817. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  4818. else:
  4819. for filename in filenames:
  4820. if filename != '':
  4821. self.worker_task.emit({'fcn': self.open_gcode,
  4822. 'params': [filename]})
  4823. def on_file_openproject(self):
  4824. """
  4825. File menu callback for opening a project.
  4826. :return: None
  4827. """
  4828. self.report_usage("on_file_openproject")
  4829. App.log.debug("on_file_openproject()")
  4830. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4831. try:
  4832. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  4833. directory=self.get_last_folder(), filter=_filter_)
  4834. except TypeError:
  4835. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  4836. # The Qt methods above will return a QString which can cause problems later.
  4837. # So far json.dump() will fail to serialize it.
  4838. # TODO: Improve the serialization methods and remove this fix.
  4839. filename = str(filename)
  4840. if filename == "":
  4841. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  4842. else:
  4843. # self.worker_task.emit({'fcn': self.open_project,
  4844. # 'params': [filename]})
  4845. # The above was failing because open_project() is not
  4846. # thread safe. The new_project()
  4847. self.open_project(filename)
  4848. def on_file_openconfig(self):
  4849. """
  4850. File menu callback for opening a config file.
  4851. :return: None
  4852. """
  4853. self.report_usage("on_file_openconfig")
  4854. App.log.debug("on_file_openconfig()")
  4855. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  4856. try:
  4857. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4858. directory=self.data_path, filter=_filter_)
  4859. except TypeError:
  4860. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4861. filter = _filter_)
  4862. if filename == "":
  4863. self.inform.emit(_("[WARNING_NOTCL Open Config cancelled."))
  4864. else:
  4865. self.open_config_file(filename)
  4866. def on_file_exportsvg(self):
  4867. """
  4868. Callback for menu item File->Export SVG.
  4869. :return: None
  4870. """
  4871. self.report_usage("on_file_exportsvg")
  4872. App.log.debug("on_file_exportsvg()")
  4873. obj = self.collection.get_active()
  4874. if obj is None:
  4875. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4876. msg = _("Please Select a Geometry object to export")
  4877. msgbox = QtWidgets.QMessageBox()
  4878. msgbox.setInformativeText(msg)
  4879. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4880. msgbox.setDefaultButton(bt_ok)
  4881. msgbox.exec_()
  4882. return
  4883. # Check for more compatible types and add as required
  4884. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4885. and not isinstance(obj, FlatCAMExcellon)):
  4886. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  4887. msgbox = QtWidgets.QMessageBox()
  4888. msgbox.setInformativeText(msg)
  4889. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4890. msgbox.setDefaultButton(bt_ok)
  4891. msgbox.exec_()
  4892. return
  4893. name = self.collection.get_active().options["name"]
  4894. filter = "SVG File (*.svg);;All Files (*.*)"
  4895. try:
  4896. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4897. caption=_("Export SVG"),
  4898. directory=self.get_last_save_folder() + '/' + str(name),
  4899. filter=filter)
  4900. except TypeError:
  4901. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  4902. filename = str(filename)
  4903. if filename == "":
  4904. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  4905. return
  4906. else:
  4907. self.export_svg(name, filename)
  4908. self.file_saved.emit("SVG", filename)
  4909. def on_file_exportpng(self):
  4910. self.report_usage("on_file_exportpng")
  4911. App.log.debug("on_file_exportpng()")
  4912. image = _screenshot()
  4913. data = np.asarray(image)
  4914. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4915. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  4916. return
  4917. filter_ = "PNG File (*.png);;All Files (*.*)"
  4918. try:
  4919. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4920. caption=_("Export PNG Image"),
  4921. directory=self.get_last_save_folder() + '/png_' + self.date,
  4922. filter=filter_)
  4923. except TypeError:
  4924. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  4925. filename = str(filename)
  4926. if filename == "":
  4927. self.inform.emit(_("Export PNG cancelled."))
  4928. return
  4929. else:
  4930. write_png(filename, data)
  4931. self.file_saved.emit("png", filename)
  4932. def on_file_savegerber(self):
  4933. """
  4934. Callback for menu item File->Export Gerber.
  4935. :return: None
  4936. """
  4937. self.report_usage("on_file_savegerber")
  4938. App.log.debug("on_file_savegerber()")
  4939. obj = self.collection.get_active()
  4940. if obj is None:
  4941. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  4942. return
  4943. # Check for more compatible types and add as required
  4944. if not isinstance(obj, FlatCAMGerber):
  4945. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  4946. return
  4947. name = self.collection.get_active().options["name"]
  4948. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4949. try:
  4950. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4951. caption="Save Gerber source file",
  4952. directory=self.get_last_save_folder() + '/' + name,
  4953. filter=filter)
  4954. except TypeError:
  4955. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  4956. filename = str(filename)
  4957. if filename == "":
  4958. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  4959. return
  4960. else:
  4961. self.save_source_file(name, filename)
  4962. self.file_saved.emit("Gerber", filename)
  4963. def on_file_saveexcellon(self):
  4964. """
  4965. Callback for menu item File->Export Gerber.
  4966. :return: None
  4967. """
  4968. self.report_usage("on_file_saveexcellon")
  4969. App.log.debug("on_file_saveexcellon()")
  4970. obj = self.collection.get_active()
  4971. if obj is None:
  4972. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  4973. return
  4974. # Check for more compatible types and add as required
  4975. if not isinstance(obj, FlatCAMExcellon):
  4976. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4977. return
  4978. name = self.collection.get_active().options["name"]
  4979. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4980. try:
  4981. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4982. caption=_("Save Excellon source file"),
  4983. directory=self.get_last_save_folder() + '/' + name,
  4984. filter=filter)
  4985. except TypeError:
  4986. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  4987. filename = str(filename)
  4988. if filename == "":
  4989. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  4990. return
  4991. else:
  4992. self.save_source_file(name, filename)
  4993. self.file_saved.emit("Excellon", filename)
  4994. def on_file_exportexcellon(self):
  4995. """
  4996. Callback for menu item File->Export SVG.
  4997. :return: None
  4998. """
  4999. self.report_usage("on_file_exportexcellon")
  5000. App.log.debug("on_file_exportexcellon()")
  5001. obj = self.collection.get_active()
  5002. if obj is None:
  5003. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  5004. return
  5005. # Check for more compatible types and add as required
  5006. if not isinstance(obj, FlatCAMExcellon):
  5007. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  5008. return
  5009. name = self.collection.get_active().options["name"]
  5010. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5011. try:
  5012. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5013. caption=_("Export Excellon"),
  5014. directory=self.get_last_save_folder() + '/' + name,
  5015. filter=filter)
  5016. except TypeError:
  5017. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  5018. filename = str(filename)
  5019. if filename == "":
  5020. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  5021. return
  5022. else:
  5023. self.export_excellon(name, filename)
  5024. self.file_saved.emit("Excellon", filename)
  5025. def on_file_exportdxf(self):
  5026. """
  5027. Callback for menu item File->Export DXF.
  5028. :return: None
  5029. """
  5030. self.report_usage("on_file_exportdxf")
  5031. App.log.debug("on_file_exportdxf()")
  5032. obj = self.collection.get_active()
  5033. if obj is None:
  5034. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  5035. msg = _("Please Select a Geometry object to export")
  5036. msgbox = QtWidgets.QMessageBox()
  5037. msgbox.setInformativeText(msg)
  5038. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5039. msgbox.setDefaultButton(bt_ok)
  5040. msgbox.exec_()
  5041. return
  5042. # Check for more compatible types and add as required
  5043. if not isinstance(obj, FlatCAMGeometry):
  5044. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  5045. msgbox = QtWidgets.QMessageBox()
  5046. msgbox.setInformativeText(msg)
  5047. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5048. msgbox.setDefaultButton(bt_ok)
  5049. msgbox.exec_()
  5050. return
  5051. name = self.collection.get_active().options["name"]
  5052. filter = "DXF File (*.DXF);;All Files (*.*)"
  5053. try:
  5054. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5055. caption=_("Export DXF"),
  5056. directory=self.get_last_save_folder() + '/' + name,
  5057. filter=filter)
  5058. except TypeError:
  5059. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"), filter=filter)
  5060. filename = str(filename)
  5061. if filename == "":
  5062. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  5063. return
  5064. else:
  5065. self.export_dxf(name, filename)
  5066. self.file_saved.emit("DXF", filename)
  5067. def on_file_importsvg(self, type_of_obj):
  5068. """
  5069. Callback for menu item File->Import SVG.
  5070. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5071. :type type_of_obj: str
  5072. :return: None
  5073. """
  5074. self.report_usage("on_file_importsvg")
  5075. App.log.debug("on_file_importsvg()")
  5076. filter = "SVG File (*.svg);;All Files (*.*)"
  5077. try:
  5078. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5079. directory=self.get_last_folder(), filter=filter)
  5080. except TypeError:
  5081. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"), filter=filter)
  5082. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5083. type_of_obj = "geometry"
  5084. filenames = [str(filename) for filename in filenames]
  5085. if len(filenames) == 0:
  5086. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  5087. else:
  5088. for filename in filenames:
  5089. if filename != '':
  5090. self.worker_task.emit({'fcn': self.import_svg,
  5091. 'params': [filename, type_of_obj]})
  5092. def on_file_importdxf(self, type_of_obj):
  5093. """
  5094. Callback for menu item File->Import DXF.
  5095. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5096. :type type_of_obj: str
  5097. :return: None
  5098. """
  5099. self.report_usage("on_file_importdxf")
  5100. App.log.debug("on_file_importdxf()")
  5101. filter = "DXF File (*.DXF);;All Files (*.*)"
  5102. try:
  5103. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5104. directory=self.get_last_folder(), filter=filter)
  5105. except TypeError:
  5106. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"), filter=filter)
  5107. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  5108. type_of_obj = "geometry"
  5109. filenames = [str(filename) for filename in filenames]
  5110. if len(filenames) == 0:
  5111. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  5112. else:
  5113. for filename in filenames:
  5114. if filename != '':
  5115. self.worker_task.emit({'fcn': self.import_dxf,
  5116. 'params': [filename, type_of_obj]})
  5117. ###################################################################################################################
  5118. ### The following section has the functions that are displayed are call the Editoe tab CNCJob Tab #################
  5119. ###################################################################################################################
  5120. def init_code_editor(self, name):
  5121. # Signals section
  5122. # Disconnect the old signals
  5123. self.ui.buttonOpen.clicked.disconnect()
  5124. self.ui.buttonSave.clicked.disconnect()
  5125. # add the tab if it was closed
  5126. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5127. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5128. # delete the absolute and relative position and messages in the infobar
  5129. self.ui.position_label.setText("")
  5130. self.ui.rel_position_label.setText("")
  5131. # first clear previous text in text editor (if any)
  5132. self.ui.code_editor.clear()
  5133. self.ui.code_editor.setReadOnly(False)
  5134. self.toggle_codeeditor = True
  5135. self.ui.code_editor.completer_enable = False
  5136. # Switch plot_area to CNCJob tab
  5137. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5138. def on_view_source(self):
  5139. try:
  5140. obj = self.collection.get_active()
  5141. except:
  5142. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5143. return 'fail'
  5144. # then append the text from GCode to the text editor
  5145. try:
  5146. file = StringIO(obj.source_file)
  5147. except AttributeError:
  5148. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5149. return 'fail'
  5150. if obj.kind == 'gerber':
  5151. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5152. elif obj.kind == 'excellon':
  5153. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5154. self.init_code_editor(name=_("Source Editor"))
  5155. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5156. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5157. try:
  5158. for line in file:
  5159. proc_line = str(line).strip('\n')
  5160. self.ui.code_editor.append(proc_line)
  5161. except Exception as e:
  5162. log.debug('App.on_view_source() -->%s' % str(e))
  5163. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5164. return
  5165. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5166. self.handleTextChanged()
  5167. self.ui.show()
  5168. def on_toggle_code_editor(self):
  5169. self.report_usage("on_toggle_code_editor()")
  5170. if self.toggle_codeeditor is False:
  5171. self.init_code_editor(name=_("Code Editor"))
  5172. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5173. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5174. else:
  5175. for idx in range(self.ui.plot_tab_area.count()):
  5176. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5177. self.ui.plot_tab_area.closeTab(idx)
  5178. break
  5179. self.toggle_codeeditor = False
  5180. def on_filenewscript(self):
  5181. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5182. self.init_code_editor(name=_("Script Editor"))
  5183. self.ui.code_editor.completer_enable = True
  5184. self.ui.code_editor.append(_(
  5185. "#\n"
  5186. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5187. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5188. "#\n\n"
  5189. "# FlatCAM commands list:\n"
  5190. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5191. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5192. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5193. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5194. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5195. "# WriteGCode\n"
  5196. "#\n\n"
  5197. ))
  5198. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5199. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5200. self.handleTextChanged()
  5201. self.ui.code_editor.show()
  5202. def on_fileopenscript(self):
  5203. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5204. try:
  5205. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5206. directory=self.get_last_folder(), filter=_filter_)
  5207. except TypeError:
  5208. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5209. # The Qt methods above will return a QString which can cause problems later.
  5210. # So far json.dump() will fail to serialize it.
  5211. # TODO: Improve the serialization methods and remove this fix.
  5212. filename = str(filename)
  5213. if filename == "":
  5214. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5215. else:
  5216. self.on_filenewscript()
  5217. try:
  5218. with open(filename, "r") as opened_script:
  5219. try:
  5220. for line in opened_script:
  5221. proc_line = str(line).strip('\n')
  5222. self.ui.code_editor.append(proc_line)
  5223. except Exception as e:
  5224. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5225. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5226. return
  5227. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5228. self.handleTextChanged()
  5229. self.ui.show()
  5230. except Exception as e:
  5231. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5232. def on_filerunscript(self, name=None):
  5233. """
  5234. File menu callback for loading and running a TCL script.
  5235. :return: None
  5236. """
  5237. self.report_usage("on_filerunscript")
  5238. App.log.debug("on_file_runscript()")
  5239. if name:
  5240. filename = name
  5241. else:
  5242. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5243. try:
  5244. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  5245. directory=self.get_last_folder(), filter=_filter_)
  5246. except TypeError:
  5247. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  5248. # The Qt methods above will return a QString which can cause problems later.
  5249. # So far json.dump() will fail to serialize it.
  5250. # TODO: Improve the serialization methods and remove this fix.
  5251. filename = str(filename)
  5252. if filename == "":
  5253. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  5254. else:
  5255. try:
  5256. with open(filename, "r") as tcl_script:
  5257. cmd_line_shellfile_content = tcl_script.read()
  5258. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  5259. except Exception as e:
  5260. log.debug("App.on_filerunscript() -> %s" % str(e))
  5261. sys.exit(2)
  5262. def on_file_saveproject(self):
  5263. """
  5264. Callback for menu item File->Save Project. Saves the project to
  5265. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  5266. if set to None. The project is saved by calling ``self.save_project()``.
  5267. :return: None
  5268. """
  5269. self.report_usage("on_file_saveproject")
  5270. if self.project_filename is None:
  5271. self.on_file_saveprojectas()
  5272. else:
  5273. self.worker_task.emit({'fcn': self.save_project,
  5274. 'params': [self.project_filename]})
  5275. self.file_opened.emit("project", self.project_filename)
  5276. self.file_saved.emit("project", self.project_filename)
  5277. self.should_we_save = False
  5278. def on_file_saveprojectas(self, make_copy=False, thread=True, quit=False):
  5279. """
  5280. Callback for menu item File->Save Project As... Opens a file
  5281. chooser and saves the project to the given file via
  5282. ``self.save_project()``.
  5283. :return: None
  5284. """
  5285. self.report_usage("on_file_saveprojectas")
  5286. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  5287. try:
  5288. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5289. caption=_("Save Project As ..."),
  5290. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  5291. filter=filter_)
  5292. except TypeError:
  5293. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  5294. filename = str(filename)
  5295. if filename == '':
  5296. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  5297. return
  5298. try:
  5299. f = open(filename, 'r')
  5300. f.close()
  5301. exists = True
  5302. except IOError:
  5303. exists = False
  5304. if thread is True:
  5305. self.worker_task.emit({'fcn': self.save_project,
  5306. 'params': [filename, quit]})
  5307. else:
  5308. self.save_project(filename, quit)
  5309. # self.save_project(filename)
  5310. self.file_opened.emit("project", filename)
  5311. self.file_saved.emit("project", filename)
  5312. if not make_copy:
  5313. self.project_filename = filename
  5314. self.should_we_save = False
  5315. def export_svg(self, obj_name, filename, scale_factor=0.00):
  5316. """
  5317. Exports a Geometry Object to an SVG file.
  5318. :param filename: Path to the SVG file to save to.
  5319. :return:
  5320. """
  5321. self.report_usage("export_svg()")
  5322. if filename is None:
  5323. filename = self.defaults["global_last_save_folder"]
  5324. self.log.debug("export_svg()")
  5325. try:
  5326. obj = self.collection.get_by_name(str(obj_name))
  5327. except:
  5328. # TODO: The return behavior has not been established... should raise exception?
  5329. return "Could not retrieve object: %s" % obj_name
  5330. with self.proc_container.new(_("Exporting SVG")) as proc:
  5331. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5332. # Determine bounding area for svg export
  5333. bounds = obj.bounds()
  5334. size = obj.size()
  5335. # Convert everything to strings for use in the xml doc
  5336. svgwidth = str(size[0])
  5337. svgheight = str(size[1])
  5338. minx = str(bounds[0])
  5339. miny = str(bounds[1] - size[1])
  5340. uom = obj.units.lower()
  5341. # Add a SVG Header and footer to the svg output from shapely
  5342. # The transform flips the Y Axis so that everything renders
  5343. # properly within svg apps such as inkscape
  5344. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5345. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5346. svg_header += 'width="' + svgwidth + uom + '" '
  5347. svg_header += 'height="' + svgheight + uom + '" '
  5348. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  5349. svg_header += '<g transform="scale(1,-1)">'
  5350. svg_footer = '</g> </svg>'
  5351. svg_elem = svg_header + exported_svg + svg_footer
  5352. # Parse the xml through a xml parser just to add line feeds
  5353. # and to make it look more pretty for the output
  5354. svgcode = parse_xml_string(svg_elem)
  5355. with open(filename, 'w') as fp:
  5356. fp.write(svgcode.toprettyxml())
  5357. self.file_saved.emit("SVG", filename)
  5358. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5359. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  5360. """
  5361. Exports a Geometry Object to an SVG file in negative.
  5362. :param filename: Path to the SVG file to save to.
  5363. :param: use_thread: If True use threads
  5364. :type: Bool
  5365. :return:
  5366. """
  5367. self.report_usage("export_negative()")
  5368. if filename is None:
  5369. filename = self.defaults["global_last_save_folder"]
  5370. self.log.debug("export_svg() negative")
  5371. try:
  5372. obj = self.collection.get_by_name(str(obj_name))
  5373. except:
  5374. # TODO: The return behavior has not been established... should raise exception?
  5375. return "Could not retrieve object: %s" % obj_name
  5376. try:
  5377. box = self.collection.get_by_name(str(box_name))
  5378. except:
  5379. # TODO: The return behavior has not been established... should raise exception?
  5380. return "Could not retrieve object: %s" % box_name
  5381. if box is None:
  5382. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5383. box = obj
  5384. def make_negative_film():
  5385. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5386. self.progress.emit(40)
  5387. # Determine bounding area for svg export
  5388. bounds = box.bounds()
  5389. size = box.size()
  5390. uom = obj.units.lower()
  5391. # Convert everything to strings for use in the xml doc
  5392. svgwidth = str(size[0] + (2 * boundary))
  5393. svgheight = str(size[1] + (2 * boundary))
  5394. minx = str(bounds[0] - boundary)
  5395. miny = str(bounds[1] + boundary + size[1])
  5396. miny_rect = str(bounds[1] - boundary)
  5397. # Add a SVG Header and footer to the svg output from shapely
  5398. # The transform flips the Y Axis so that everything renders
  5399. # properly within svg apps such as inkscape
  5400. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5401. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5402. svg_header += 'width="' + svgwidth + uom + '" '
  5403. svg_header += 'height="' + svgheight + uom + '" '
  5404. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5405. svg_header += '>'
  5406. svg_header += '<g transform="scale(1,-1)">'
  5407. svg_footer = '</g> </svg>'
  5408. self.progress.emit(60)
  5409. # Change the attributes of the exported SVG
  5410. # We don't need stroke-width - wrong, we do when we have lines with certain width
  5411. # We set opacity to maximum
  5412. # We set the color to WHITE
  5413. root = ET.fromstring(exported_svg)
  5414. for child in root:
  5415. child.set('fill', '#FFFFFF')
  5416. child.set('opacity', '1.0')
  5417. child.set('stroke', '#FFFFFF')
  5418. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  5419. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  5420. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  5421. first_svg_elem_tag = 'rect'
  5422. first_svg_elem_attribs = {
  5423. 'x': minx,
  5424. 'y': miny_rect,
  5425. 'width': svgwidth,
  5426. 'height': svgheight,
  5427. 'id': 'neg_rect',
  5428. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  5429. }
  5430. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  5431. exported_svg = ET.tostring(root)
  5432. svg_elem = svg_header + str(exported_svg) + svg_footer
  5433. self.progress.emit(80)
  5434. # Parse the xml through a xml parser just to add line feeds
  5435. # and to make it look more pretty for the output
  5436. doc = parse_xml_string(svg_elem)
  5437. with open(filename, 'w') as fp:
  5438. fp.write(doc.toprettyxml())
  5439. self.progress.emit(100)
  5440. self.file_saved.emit("SVG", filename)
  5441. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5442. if use_thread is True:
  5443. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5444. def job_thread_film(app_obj):
  5445. try:
  5446. make_negative_film()
  5447. except Exception as e:
  5448. proc.done()
  5449. return
  5450. proc.done()
  5451. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5452. else:
  5453. make_negative_film()
  5454. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5455. """
  5456. Exports a Geometry Object to an SVG file in negative.
  5457. :param filename: Path to the SVG file to save to.
  5458. :param: use_thread: If True use threads
  5459. :type: Bool
  5460. :return:
  5461. """
  5462. self.report_usage("export_svg_black()")
  5463. if filename is None:
  5464. filename = self.defaults["global_last_save_folder"]
  5465. self.log.debug("export_svg() black")
  5466. try:
  5467. obj = self.collection.get_by_name(str(obj_name))
  5468. except:
  5469. # TODO: The return behavior has not been established... should raise exception?
  5470. return "Could not retrieve object: %s" % obj_name
  5471. try:
  5472. box = self.collection.get_by_name(str(box_name))
  5473. except:
  5474. # TODO: The return behavior has not been established... should raise exception?
  5475. return "Could not retrieve object: %s" % box_name
  5476. if box is None:
  5477. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5478. box = obj
  5479. def make_black_film():
  5480. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5481. self.progress.emit(40)
  5482. # Change the attributes of the exported SVG
  5483. # We don't need stroke-width
  5484. # We set opacity to maximum
  5485. # We set the colour to WHITE
  5486. root = ET.fromstring(exported_svg)
  5487. for child in root:
  5488. child.set('fill', '#000000')
  5489. child.set('opacity', '1.0')
  5490. child.set('stroke', '#000000')
  5491. exported_svg = ET.tostring(root)
  5492. # Determine bounding area for svg export
  5493. bounds = box.bounds()
  5494. size = box.size()
  5495. # This contain the measure units
  5496. uom = obj.units.lower()
  5497. # Define a boundary around SVG of about 1.0mm (~39mils)
  5498. if uom in "mm":
  5499. boundary = 1.0
  5500. else:
  5501. boundary = 0.0393701
  5502. self.progress.emit(80)
  5503. # Convert everything to strings for use in the xml doc
  5504. svgwidth = str(size[0] + (2 * boundary))
  5505. svgheight = str(size[1] + (2 * boundary))
  5506. minx = str(bounds[0] - boundary)
  5507. miny = str(bounds[1] + boundary + size[1])
  5508. self.log.debug(minx)
  5509. self.log.debug(miny)
  5510. # Add a SVG Header and footer to the svg output from shapely
  5511. # The transform flips the Y Axis so that everything renders
  5512. # properly within svg apps such as inkscape
  5513. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5514. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5515. svg_header += 'width="' + svgwidth + uom + '" '
  5516. svg_header += 'height="' + svgheight + uom + '" '
  5517. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5518. svg_header += '>'
  5519. svg_header += '<g transform="scale(1,-1)">'
  5520. svg_footer = '</g> </svg>'
  5521. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5522. self.progress.emit(90)
  5523. # Parse the xml through a xml parser just to add line feeds
  5524. # and to make it look more pretty for the output
  5525. doc = parse_xml_string(svg_elem)
  5526. with open(filename, 'w') as fp:
  5527. fp.write(doc.toprettyxml())
  5528. self.progress.emit(100)
  5529. self.file_saved.emit("SVG", filename)
  5530. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5531. if use_thread is True:
  5532. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5533. def job_thread_film(app_obj):
  5534. try:
  5535. make_black_film()
  5536. except Exception as e:
  5537. proc.done()
  5538. return
  5539. proc.done()
  5540. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5541. else:
  5542. make_black_film()
  5543. def save_source_file(self, obj_name, filename, use_thread=True):
  5544. """
  5545. Exports a Gerber Object to an Gerber file.
  5546. :param filename: Path to the Gerber file to save to.
  5547. :return:
  5548. """
  5549. self.report_usage("save source file()")
  5550. if filename is None:
  5551. filename = self.defaults["global_last_save_folder"]
  5552. self.log.debug("save source file()")
  5553. obj = self.collection.get_by_name(obj_name)
  5554. file_string = StringIO(obj.source_file)
  5555. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5556. with open(filename, 'w') as file:
  5557. file.writelines('G04*\n')
  5558. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5559. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5560. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5561. file.writelines('G04 Created on : %s*\n' % time_string)
  5562. for line in file_string:
  5563. file.writelines(line)
  5564. def export_excellon(self, obj_name, filename, use_thread=True):
  5565. """
  5566. Exports a Excellon Object to an Excellon file.
  5567. :param filename: Path to the Excellon file to save to.
  5568. :return:
  5569. """
  5570. self.report_usage("export_excellon()")
  5571. if filename is None:
  5572. filename = self.defaults["global_last_save_folder"]
  5573. self.log.debug("export_excellon()")
  5574. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5575. self.defaults["excellon_exp_decimals"]
  5576. )
  5577. units = ''
  5578. try:
  5579. obj = self.collection.get_by_name(str(obj_name))
  5580. except:
  5581. # TODO: The return behavior has not been established... should raise exception?
  5582. return "Could not retrieve object: %s" % obj_name
  5583. # updated units
  5584. eunits = self.defaults["excellon_exp_units"]
  5585. ewhole = self.defaults["excellon_exp_integer"]
  5586. efract = self.defaults["excellon_exp_decimals"]
  5587. ezeros = self.defaults["excellon_exp_zeros"]
  5588. eformat = self.defaults[ "excellon_exp_format"]
  5589. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5590. if fc_units == 'MM':
  5591. factor = 1 if eunits == 'METRIC' else 0.03937
  5592. else:
  5593. factor = 25.4 if eunits == 'METRIC' else 1
  5594. def make_excellon():
  5595. try:
  5596. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5597. header = 'M48\n'
  5598. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5599. (str(self.version), str(self.version_date))
  5600. header += ';Filename: %s' % str(obj_name) + '\n'
  5601. header += ';Created on : %s' % time_str + '\n'
  5602. if eformat == 'dec':
  5603. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5604. header += eunits + '\n'
  5605. for tool in obj.tools:
  5606. if eunits == 'METRIC':
  5607. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5608. tool=str(tool),
  5609. dec=2)
  5610. else:
  5611. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5612. tool=str(tool),
  5613. dec=4)
  5614. else:
  5615. if ezeros == 'LZ':
  5616. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5617. form='ndec', e_zeros='LZ', factor=factor)
  5618. header += '%s,%s\n' % (eunits, 'LZ')
  5619. header += format_exc
  5620. for tool in obj.tools:
  5621. if eunits == 'METRIC':
  5622. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5623. tool=str(tool),
  5624. dec=2)
  5625. else:
  5626. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5627. tool=str(tool),
  5628. dec=4)
  5629. else:
  5630. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5631. form='ndec', e_zeros='TZ', factor=factor)
  5632. header += '%s,%s\n' % (eunits, 'TZ')
  5633. header += format_exc
  5634. for tool in obj.tools:
  5635. if eunits == 'METRIC':
  5636. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5637. tool=str(tool),
  5638. dec=2)
  5639. else:
  5640. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5641. tool=str(tool),
  5642. dec=4)
  5643. header += '%\n'
  5644. footer = 'M30\n'
  5645. exported_excellon = header
  5646. exported_excellon += excellon_code
  5647. exported_excellon += footer
  5648. with open(filename, 'w') as fp:
  5649. fp.write(exported_excellon)
  5650. self.file_saved.emit("Excellon", filename)
  5651. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5652. except Exception as e:
  5653. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5654. return 'fail'
  5655. if use_thread is True:
  5656. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5657. def job_thread_exc(app_obj):
  5658. ret = make_excellon()
  5659. if ret == 'fail':
  5660. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5661. return
  5662. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5663. else:
  5664. ret = make_excellon()
  5665. if ret == 'fail':
  5666. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5667. return
  5668. def export_dxf(self, obj_name, filename, use_thread=True):
  5669. """
  5670. Exports a Geometry Object to an DXF file.
  5671. :param filename: Path to the DXF file to save to.
  5672. :return:
  5673. """
  5674. self.report_usage("export_dxf()")
  5675. if filename is None:
  5676. filename = self.defaults["global_last_save_folder"]
  5677. self.log.debug("export_dxf()")
  5678. format_exc = ''
  5679. units = ''
  5680. try:
  5681. obj = self.collection.get_by_name(str(obj_name))
  5682. except:
  5683. # TODO: The return behavior has not been established... should raise exception?
  5684. return "Could not retrieve object: %s" % obj_name
  5685. # updated units
  5686. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5687. if units == 'IN' or units == 'INCH':
  5688. units = 'INCH'
  5689. elif units == 'MM' or units == 'METIRC':
  5690. units ='METRIC'
  5691. def make_dxf():
  5692. try:
  5693. dxf_code = obj.export_dxf()
  5694. dxf_code.saveas(filename)
  5695. self.file_saved.emit("DXF", filename)
  5696. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  5697. except:
  5698. return 'fail'
  5699. if use_thread is True:
  5700. with self.proc_container.new(_("Exporting DXF")) as proc:
  5701. def job_thread_exc(app_obj):
  5702. ret = make_dxf()
  5703. if ret == 'fail':
  5704. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5705. return
  5706. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5707. else:
  5708. ret = make_dxf()
  5709. if ret == 'fail':
  5710. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5711. return
  5712. def import_svg(self, filename, geo_type='geometry', outname=None):
  5713. """
  5714. Adds a new Geometry Object to the projects and populates
  5715. it with shapes extracted from the SVG file.
  5716. :param filename: Path to the SVG file.
  5717. :param outname:
  5718. :return:
  5719. """
  5720. self.report_usage("import_svg()")
  5721. obj_type = ""
  5722. if geo_type is None or geo_type == "geometry":
  5723. obj_type = "geometry"
  5724. elif geo_type == "gerber":
  5725. obj_type = geo_type
  5726. else:
  5727. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5728. "Only Geometry and Gerber are supported"))
  5729. return
  5730. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5731. def obj_init(geo_obj, app_obj):
  5732. geo_obj.import_svg(filename, obj_type, units=units)
  5733. geo_obj.multigeo = False
  5734. with self.proc_container.new(_("Importing SVG")) as proc:
  5735. # Object name
  5736. name = outname or filename.split('/')[-1].split('\\')[-1]
  5737. self.new_object(obj_type, name, obj_init, autoselected=False)
  5738. self.progress.emit(20)
  5739. # Register recent file
  5740. self.file_opened.emit("svg", filename)
  5741. # GUI feedback
  5742. self.inform.emit(_("[success] Opened: %s") % filename)
  5743. self.progress.emit(100)
  5744. def import_dxf(self, filename, geo_type='geometry', outname=None):
  5745. """
  5746. Adds a new Geometry Object to the projects and populates
  5747. it with shapes extracted from the DXF file.
  5748. :param filename: Path to the DXF file.
  5749. :param outname:
  5750. :type putname: str
  5751. :return:
  5752. """
  5753. self.report_usage("import_dxf()")
  5754. obj_type = ""
  5755. if geo_type is None or geo_type == "geometry":
  5756. obj_type = "geometry"
  5757. elif geo_type == "gerber":
  5758. obj_type = geo_type
  5759. else:
  5760. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5761. "Only Geometry and Gerber are supported"))
  5762. return
  5763. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5764. def obj_init(geo_obj, app_obj):
  5765. geo_obj.import_dxf(filename, obj_type, units=units)
  5766. geo_obj.multigeo = False
  5767. with self.proc_container.new(_("Importing DXF")) as proc:
  5768. # Object name
  5769. name = outname or filename.split('/')[-1].split('\\')[-1]
  5770. self.new_object(obj_type, name, obj_init, autoselected=False)
  5771. self.progress.emit(20)
  5772. # Register recent file
  5773. self.file_opened.emit("dxf", filename)
  5774. # GUI feedback
  5775. self.inform.emit(_("[success] Opened: %s") % filename)
  5776. self.progress.emit(100)
  5777. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  5778. """
  5779. Adds a new Geometry Object to the projects and populates
  5780. it with shapes extracted from the SVG file.
  5781. :param filename: Path to the SVG file.
  5782. :param outname:
  5783. :return:
  5784. """
  5785. self.report_usage("import_image()")
  5786. obj_type = ""
  5787. if type is None or type == "geometry":
  5788. obj_type = "geometry"
  5789. elif type == "gerber":
  5790. obj_type = type
  5791. else:
  5792. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5793. "Only Geometry and Gerber are supported"))
  5794. return
  5795. def obj_init(geo_obj, app_obj):
  5796. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  5797. geo_obj.multigeo = False
  5798. with self.proc_container.new(_("Importing Image")) as proc:
  5799. # Object name
  5800. name = outname or filename.split('/')[-1].split('\\')[-1]
  5801. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  5802. self.new_object(obj_type, name, obj_init)
  5803. self.progress.emit(20)
  5804. # Register recent file
  5805. self.file_opened.emit("image", filename)
  5806. # GUI feedback
  5807. self.inform.emit(_("[success] Opened: %s") % filename)
  5808. self.progress.emit(100)
  5809. def open_gerber(self, filename, outname=None):
  5810. """
  5811. Opens a Gerber file, parses it and creates a new object for
  5812. it in the program. Thread-safe.
  5813. :param outname: Name of the resulting object. None causes the
  5814. name to be that of the file.
  5815. :param filename: Gerber file filename
  5816. :type filename: str
  5817. :param follow: If true, the parser will not create polygons, just lines
  5818. following the gerber path.
  5819. :type follow: bool
  5820. :return: None
  5821. """
  5822. # How the object should be initialized
  5823. def obj_init(gerber_obj, app_obj):
  5824. assert isinstance(gerber_obj, FlatCAMGerber), \
  5825. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  5826. # Opening the file happens here
  5827. self.progress.emit(30)
  5828. try:
  5829. gerber_obj.parse_file(filename)
  5830. except IOError:
  5831. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  5832. app_obj.progress.emit(0)
  5833. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  5834. return "fail"
  5835. except ParseError as err:
  5836. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename, error=str(err)))
  5837. app_obj.progress.emit(0)
  5838. self.log.error(str(err))
  5839. return "fail"
  5840. except:
  5841. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  5842. msg += traceback.format_exc()
  5843. app_obj.inform.emit(msg)
  5844. return "fail"
  5845. if gerber_obj.is_empty():
  5846. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  5847. # self.collection.set_active(gerber_obj.options["name"])
  5848. # self.collection.delete_active()
  5849. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  5850. return "fail"
  5851. # Further parsing
  5852. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  5853. App.log.debug("open_gerber()")
  5854. with self.proc_container.new(_("Opening Gerber")) as proc:
  5855. self.progress.emit(10)
  5856. # Object name
  5857. name = outname or filename.split('/')[-1].split('\\')[-1]
  5858. ### Object creation ###
  5859. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  5860. if ret == 'fail':
  5861. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  5862. return
  5863. # Register recent file
  5864. self.file_opened.emit("gerber", filename)
  5865. self.progress.emit(100)
  5866. # GUI feedback
  5867. self.inform.emit(_("[success] Opened: %s") % filename)
  5868. def open_excellon(self, filename, outname=None):
  5869. """
  5870. Opens an Excellon file, parses it and creates a new object for
  5871. it in the program. Thread-safe.
  5872. :param outname: Name of the resulting object. None causes the
  5873. name to be that of the file.
  5874. :param filename: Excellon file filename
  5875. :type filename: str
  5876. :return: None
  5877. """
  5878. App.log.debug("open_excellon()")
  5879. #self.progress.emit(10)
  5880. # How the object should be initialized
  5881. def obj_init(excellon_obj, app_obj):
  5882. # self.progress.emit(20)
  5883. try:
  5884. ret = excellon_obj.parse_file(filename=filename)
  5885. if ret == "fail":
  5886. log.debug("Excellon parsing failed.")
  5887. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  5888. return "fail"
  5889. except IOError:
  5890. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  5891. log.debug("Could not open Excellon object.")
  5892. self.progress.emit(0) # TODO: self and app_bjj mixed
  5893. return "fail"
  5894. except:
  5895. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  5896. msg += traceback.format_exc()
  5897. app_obj.inform.emit(msg)
  5898. return "fail"
  5899. ret = excellon_obj.create_geometry()
  5900. if ret == 'fail':
  5901. log.debug("Could not create geometry for Excellon object.")
  5902. return "fail"
  5903. # if excellon_obj.is_empty():
  5904. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5905. # return "fail"
  5906. for tool in excellon_obj.tools:
  5907. if excellon_obj.tools[tool]['solid_geometry']:
  5908. return
  5909. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  5910. return "fail"
  5911. with self.proc_container.new(_("Opening Excellon.")):
  5912. # Object name
  5913. name = outname or filename.split('/')[-1].split('\\')[-1]
  5914. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5915. if ret == 'fail':
  5916. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  5917. return
  5918. # Register recent file
  5919. self.file_opened.emit("excellon", filename)
  5920. # GUI feedback
  5921. self.inform.emit(_("[success] Opened: %s") % filename)
  5922. # self.progress.emit(100)
  5923. def open_gcode(self, filename, outname=None):
  5924. """
  5925. Opens a G-gcode file, parses it and creates a new object for
  5926. it in the program. Thread-safe.
  5927. :param outname: Name of the resulting object. None causes the
  5928. name to be that of the file.
  5929. :param filename: G-code file filename
  5930. :type filename: str
  5931. :return: None
  5932. """
  5933. App.log.debug("open_gcode()")
  5934. # How the object should be initialized
  5935. def obj_init(job_obj, app_obj_):
  5936. """
  5937. :type app_obj_: App
  5938. """
  5939. assert isinstance(app_obj_, App), \
  5940. "Initializer expected App, got %s" % type(app_obj_)
  5941. self.progress.emit(10)
  5942. try:
  5943. f = open(filename)
  5944. gcode = f.read()
  5945. f.close()
  5946. except IOError:
  5947. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  5948. self.progress.emit(0)
  5949. return "fail"
  5950. job_obj.gcode = gcode
  5951. self.progress.emit(20)
  5952. ret = job_obj.gcode_parse()
  5953. if ret == "fail":
  5954. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  5955. return "fail"
  5956. self.progress.emit(60)
  5957. job_obj.create_geometry()
  5958. with self.proc_container.new(_("Opening G-Code.")):
  5959. # Object name
  5960. name = outname or filename.split('/')[-1].split('\\')[-1]
  5961. # New object creation and file processing
  5962. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5963. if ret == 'fail':
  5964. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5965. "Attempting to create a FlatCAM CNCJob Object from "
  5966. "G-Code file failed during processing"))
  5967. return "fail"
  5968. # Register recent file
  5969. self.file_opened.emit("cncjob", filename)
  5970. # GUI feedback
  5971. self.inform.emit(_("[success] Opened: %s") % filename)
  5972. self.progress.emit(100)
  5973. def open_config_file(self, filename, run_from_arg=None):
  5974. """
  5975. Loads a config file from the specified file.
  5976. :param filename: Name of the file from which to load.
  5977. :type filename: str
  5978. :return: None
  5979. """
  5980. App.log.debug("Opening config file: " + filename)
  5981. # add the tab if it was closed
  5982. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  5983. # first clear previous text in text editor (if any)
  5984. self.ui.code_editor.clear()
  5985. # Switch plot_area to CNCJob tab
  5986. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5987. try:
  5988. if filename:
  5989. f = QtCore.QFile(filename)
  5990. if f.open(QtCore.QIODevice.ReadOnly):
  5991. stream = QtCore.QTextStream(f)
  5992. gcode_edited = stream.readAll()
  5993. self.ui.code_editor.setPlainText(gcode_edited)
  5994. f.close()
  5995. except IOError:
  5996. App.log.error("Failed to open config file: %s" % filename)
  5997. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  5998. return
  5999. def open_project(self, filename, run_from_arg=None):
  6000. """
  6001. Loads a project from the specified file.
  6002. 1) Loads and parses file
  6003. 2) Registers the file as recently opened.
  6004. 3) Calls on_file_new()
  6005. 4) Updates options
  6006. 5) Calls new_object() with the object's from_dict() as init method.
  6007. 6) Calls plot_all()
  6008. :param filename: Name of the file from which to load.
  6009. :type filename: str
  6010. :return: None
  6011. """
  6012. App.log.debug("Opening project: " + filename)
  6013. # Open and parse an uncompressed Project file
  6014. try:
  6015. f = open(filename, 'r')
  6016. except IOError:
  6017. App.log.error("Failed to open project file: %s" % filename)
  6018. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6019. return
  6020. try:
  6021. d = json.load(f, object_hook=dict2obj)
  6022. except:
  6023. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s" % filename)
  6024. f.close()
  6025. # Open and parse a compressed Project file
  6026. try:
  6027. with lzma.open(filename) as f:
  6028. file_content = f.read().decode('utf-8')
  6029. d = json.loads(file_content, object_hook=dict2obj)
  6030. except IOError:
  6031. App.log.error("Failed to open project file: %s" % filename)
  6032. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  6033. return
  6034. self.file_opened.emit("project", filename)
  6035. # Clear the current project
  6036. ## NOT THREAD SAFE ##
  6037. if run_from_arg is True:
  6038. pass
  6039. else:
  6040. self.on_file_new()
  6041. #Project options
  6042. self.options.update(d['options'])
  6043. self.project_filename = filename
  6044. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  6045. self.set_screen_units(self.options["units"])
  6046. # Re create objects
  6047. App.log.debug("Re-creating objects...")
  6048. for obj in d['objs']:
  6049. def obj_init(obj_inst, app_inst):
  6050. obj_inst.from_dict(obj)
  6051. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  6052. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  6053. self.plot_all()
  6054. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  6055. self.should_we_save = False
  6056. App.log.debug("Project loaded")
  6057. def propagate_defaults(self, silent=False):
  6058. """
  6059. This method is used to set default values in classes. It's
  6060. an alternative to project options but allows the use
  6061. of values invisible to the user.
  6062. :return: None
  6063. """
  6064. if silent is False:
  6065. self.log.debug("propagate_defaults()")
  6066. # Which objects to update the given parameters.
  6067. routes = {
  6068. "global_zdownrate": CNCjob,
  6069. "excellon_zeros": Excellon,
  6070. "excellon_format_upper_in": Excellon,
  6071. "excellon_format_lower_in": Excellon,
  6072. "excellon_format_upper_mm": Excellon,
  6073. "excellon_format_lower_mm": Excellon,
  6074. "excellon_units": Excellon,
  6075. "gerber_use_buffer_for_union": Gerber,
  6076. "geometry_multidepth": Geometry
  6077. }
  6078. for param in routes:
  6079. if param in routes[param].defaults:
  6080. try:
  6081. routes[param].defaults[param] = self.defaults[param]
  6082. if silent is False:
  6083. self.log.debug(" " + param + " OK")
  6084. except KeyError:
  6085. if silent is False:
  6086. self.log.debug(" ERROR: " + param + " not in defaults.")
  6087. else:
  6088. # Try extracting the name:
  6089. # classname_param here is param in the object
  6090. if param.find(routes[param].__name__.lower() + "_") == 0:
  6091. p = param[len(routes[param].__name__) + 1:]
  6092. if p in routes[param].defaults:
  6093. routes[param].defaults[p] = self.defaults[param]
  6094. if silent is False:
  6095. self.log.debug(" " + param + " OK!")
  6096. def restore_main_win_geom(self):
  6097. try:
  6098. self.ui.setGeometry(self.defaults["global_def_win_x"],
  6099. self.defaults["global_def_win_y"],
  6100. self.defaults["global_def_win_w"],
  6101. self.defaults["global_def_win_h"])
  6102. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  6103. settings = QSettings("Open Source", "FlatCAM")
  6104. if settings.contains("maximized_gui"):
  6105. maximized_ui = settings.value('maximized_gui', type=bool)
  6106. if maximized_ui is True:
  6107. self.ui.showMaximized()
  6108. except KeyError as e:
  6109. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  6110. def plot_all(self, zoom=True):
  6111. """
  6112. Re-generates all plots from all objects.
  6113. :return: None
  6114. """
  6115. self.log.debug("Plot_all()")
  6116. for obj in self.collection.get_list():
  6117. def worker_task(obj):
  6118. with self.proc_container.new("Plotting"):
  6119. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  6120. if zoom:
  6121. self.object_plotted.emit(obj)
  6122. # Send to worker
  6123. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  6124. # self.progress.emit(10)
  6125. #
  6126. # def worker_task(app_obj):
  6127. # print "worker task"
  6128. # percentage = 0.1
  6129. # try:
  6130. # delta = 0.9 / len(self.collection.get_list())
  6131. # except ZeroDivisionError:
  6132. # self.progress.emit(0)
  6133. # return
  6134. # for obj in self.collection.get_list():
  6135. # with self.proc_container.new("Plotting"):
  6136. # obj.plot()
  6137. # app_obj.object_plotted.emit(obj)
  6138. #
  6139. # percentage += delta
  6140. # self.progress.emit(int(percentage*100))
  6141. #
  6142. # self.progress.emit(0)
  6143. # self.plots_updated.emit()
  6144. #
  6145. # # Send to worker
  6146. # #self.worker.add_task(worker_task, [self])
  6147. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6148. def register_folder(self, filename):
  6149. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6150. def register_save_folder(self, filename):
  6151. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6152. def set_progress_bar(self, percentage, text=""):
  6153. self.ui.progress_bar.setValue(int(percentage))
  6154. def setup_shell(self):
  6155. """
  6156. Creates shell functions. Runs once at startup.
  6157. :return: None
  6158. """
  6159. self.log.debug("setup_shell()")
  6160. def shelp(p=None):
  6161. if not p:
  6162. return _("Available commands:\n") + \
  6163. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  6164. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  6165. if p not in commands:
  6166. return "Unknown command: %s" % p
  6167. return commands[p]["help"]
  6168. # --- Migrated to new architecture ---
  6169. # def options(name):
  6170. # ops = self.collection.get_by_name(str(name)).options
  6171. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  6172. def h(*args):
  6173. """
  6174. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  6175. and standalone parameters into list.
  6176. """
  6177. kwa = {}
  6178. a = []
  6179. n = len(args)
  6180. name = None
  6181. for i in range(n):
  6182. match = re.search(r'^-([a-zA-Z].*)', args[i])
  6183. if match:
  6184. assert name is None
  6185. name = match.group(1)
  6186. continue
  6187. if name is None:
  6188. a.append(args[i])
  6189. else:
  6190. kwa[name] = args[i]
  6191. name = None
  6192. return a, kwa
  6193. @contextmanager
  6194. def wait_signal(signal, timeout=10000):
  6195. """
  6196. Block loop until signal emitted, timeout (ms) elapses
  6197. or unhandled exception happens in a thread.
  6198. :param signal: Signal to wait for.
  6199. """
  6200. loop = QtCore.QEventLoop()
  6201. # Normal termination
  6202. signal.connect(loop.quit)
  6203. # Termination by exception in thread
  6204. self.thread_exception.connect(loop.quit)
  6205. status = {'timed_out': False}
  6206. def report_quit():
  6207. status['timed_out'] = True
  6208. loop.quit()
  6209. yield
  6210. # Temporarily change how exceptions are managed.
  6211. oeh = sys.excepthook
  6212. ex = []
  6213. def except_hook(type_, value, traceback_):
  6214. ex.append(value)
  6215. oeh(type_, value, traceback_)
  6216. sys.excepthook = except_hook
  6217. # Terminate on timeout
  6218. if timeout is not None:
  6219. QtCore.QTimer.singleShot(timeout, report_quit)
  6220. #### Block ####
  6221. loop.exec_()
  6222. # Restore exception management
  6223. sys.excepthook = oeh
  6224. if ex:
  6225. self.raiseTclError(str(ex[0]))
  6226. if status['timed_out']:
  6227. raise Exception('Timed out!')
  6228. def make_docs():
  6229. output = ''
  6230. import collections
  6231. od = collections.OrderedDict(sorted(commands.items()))
  6232. for cmd_, val in od.items():
  6233. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  6234. t = val['help']
  6235. usage_i = t.find('>')
  6236. if usage_i < 0:
  6237. expl = t
  6238. output += expl + '\n\n'
  6239. continue
  6240. expl = t[:usage_i - 1]
  6241. output += expl + '\n\n'
  6242. end_usage_i = t[usage_i:].find('\n')
  6243. if end_usage_i < 0:
  6244. end_usage_i = len(t[usage_i:])
  6245. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  6246. else:
  6247. extras = t[usage_i+end_usage_i+1:]
  6248. parts = [s.strip() for s in extras.split('\n')]
  6249. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  6250. for p in parts:
  6251. output += ' ' + p + '\n\n'
  6252. return output
  6253. '''
  6254. Howto implement TCL shell commands:
  6255. All parameters passed to command should be possible to set as None and test it afterwards.
  6256. This is because we need to see error caused in tcl,
  6257. if None value as default parameter is not allowed TCL will return empty error.
  6258. Use:
  6259. def mycommand(name=None,...):
  6260. Test it like this:
  6261. if name is None:
  6262. self.raise_tcl_error('Argument name is missing.')
  6263. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  6264. otherwise we will miss it and processing will silently continue.
  6265. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  6266. which is catched in exec_command and displayed in TCL shell console with red background.
  6267. Error in console is displayed with TCL trace.
  6268. This behavior works only within main thread,
  6269. errors with promissed tasks can be catched and detected only with log.
  6270. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  6271. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  6272. '''
  6273. commands = {
  6274. 'help': {
  6275. 'fcn': shelp,
  6276. 'help': _("Shows list of commands.")
  6277. },
  6278. }
  6279. # Import/overwrite tcl commands as objects of TclCommand descendants
  6280. # This modifies the variable 'commands'.
  6281. tclCommands.register_all_commands(self, commands)
  6282. # Add commands to the tcl interpreter
  6283. for cmd in commands:
  6284. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  6285. # Make the tcl puts function return instead of print to stdout
  6286. self.tcl.eval('''
  6287. rename puts original_puts
  6288. proc puts {args} {
  6289. if {[llength $args] == 1} {
  6290. return "[lindex $args 0]"
  6291. } else {
  6292. eval original_puts $args
  6293. }
  6294. }
  6295. ''')
  6296. def setup_recent_items(self):
  6297. # TODO: Move this to constructor
  6298. icons = {
  6299. "gerber": "share/flatcam_icon16.png",
  6300. "excellon": "share/drill16.png",
  6301. 'geometry': "share/geometry16.png",
  6302. "cncjob": "share/cnc16.png",
  6303. "project": "share/project16.png",
  6304. "svg": "share/geometry16.png",
  6305. "dxf": "share/dxf16.png",
  6306. "pdf": "share/pdf32.png",
  6307. "image": "share/image16.png"
  6308. }
  6309. openers = {
  6310. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  6311. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  6312. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  6313. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  6314. 'project': self.open_project,
  6315. 'svg': self.import_svg,
  6316. 'dxf': self.import_dxf,
  6317. 'image': self.import_image,
  6318. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  6319. }
  6320. # Open file
  6321. try:
  6322. f = open(self.data_path + '/recent.json')
  6323. except IOError:
  6324. App.log.error("Failed to load recent item list.")
  6325. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  6326. return
  6327. try:
  6328. self.recent = json.load(f)
  6329. except json.scanner.JSONDecodeError:
  6330. App.log.error("Failed to parse recent item list.")
  6331. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  6332. f.close()
  6333. return
  6334. f.close()
  6335. # Closure needed to create callbacks in a loop.
  6336. # Otherwise late binding occurs.
  6337. def make_callback(func, fname):
  6338. def opener():
  6339. func(fname)
  6340. return opener
  6341. def reset_recent():
  6342. # Reset menu
  6343. self.ui.recent.clear()
  6344. self.recent = []
  6345. try:
  6346. f = open(self.data_path + '/recent.json', 'w')
  6347. except IOError:
  6348. App.log.error("Failed to open recent items file for writing.")
  6349. return
  6350. json.dump(self.recent, f)
  6351. # Reset menu
  6352. self.ui.recent.clear()
  6353. # Create menu items
  6354. for recent in self.recent:
  6355. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6356. try:
  6357. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6358. # Attach callback
  6359. o = make_callback(openers[recent["kind"]], recent['filename'])
  6360. action.triggered.connect(o)
  6361. self.ui.recent.addAction(action)
  6362. except KeyError:
  6363. App.log.error("Unsupported file type: %s" % recent["kind"])
  6364. # Last action in Recent Files menu is one that Clear the content
  6365. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  6366. clear_action.triggered.connect(reset_recent)
  6367. self.ui.recent.addSeparator()
  6368. self.ui.recent.addAction(clear_action)
  6369. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6370. # self.ui.menufilerecent.set_submenu(recent_menu)
  6371. # recent_menu.show_all()
  6372. # self.ui.recent.show()
  6373. self.log.debug("Recent items list has been populated.")
  6374. def setup_component_editor(self):
  6375. # label = QtWidgets.QLabel("Choose an item from Project")
  6376. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6377. sel_title = QtWidgets.QTextEdit(
  6378. _('<b>Shortcut Key List</b>'))
  6379. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6380. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6381. # font = self.sel_title.font()
  6382. # font.setPointSize(12)
  6383. # self.sel_title.setFont(font)
  6384. selected_text = _('''
  6385. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  6386. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6387. The normal flow when working in FlatCAM is the following:</span></p>
  6388. <ol>
  6389. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  6390. <br />
  6391. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  6392. &nbsp;</li>
  6393. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  6394. <br />
  6395. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  6396. <br />
  6397. You can change the parameters in this screen and the flow direction is like this:<br />
  6398. <br />
  6399. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  6400. </ol>
  6401. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  6402. ''')
  6403. sel_title.setText(selected_text)
  6404. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6405. self.ui.selected_scroll_area.setWidget(sel_title)
  6406. # tool_title = QtWidgets.QTextEdit(
  6407. # '<b>Shortcut Key List</b>')
  6408. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6409. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6410. # # font = self.sel_title.font()
  6411. # # font.setPointSize(12)
  6412. # # self.sel_title.setFont(font)
  6413. #
  6414. # tool_text = '''
  6415. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  6416. #
  6417. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6418. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  6419. #
  6420. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  6421. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  6422. #
  6423. # <ol>
  6424. # </ol>
  6425. #
  6426. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  6427. #
  6428. # '''
  6429. #
  6430. # tool_title.setText(tool_text)
  6431. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6432. #
  6433. # self.ui.tool_scroll_area.setWidget(tool_title)
  6434. def setup_obj_classes(self):
  6435. """
  6436. Sets up application specifics on the FlatCAMObj class.
  6437. :return: None
  6438. """
  6439. FlatCAMObj.app = self
  6440. ObjectCollection.app = self
  6441. FCProcess.app = self
  6442. FCProcessContainer.app = self
  6443. def version_check(self):
  6444. """
  6445. Checks for the latest version of the program. Alerts the
  6446. user if theirs is outdated. This method is meant to be run
  6447. in a separate thread.
  6448. :return: None
  6449. """
  6450. self.log.debug("version_check()")
  6451. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  6452. full_url = App.version_url + \
  6453. "?s=" + str(self.defaults['global_serial']) + \
  6454. "&v=" + str(self.version) + \
  6455. "&os=" + str(self.os) + \
  6456. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6457. else:
  6458. # no_stats dict; just so it won't break things on website
  6459. no_ststs_dict = {}
  6460. no_ststs_dict["global_ststs"] = {}
  6461. full_url = App.version_url + \
  6462. "?s=" + str(self.defaults['global_serial']) + \
  6463. "&v=" + str(self.version) + \
  6464. "&os=" + str(self.os) + \
  6465. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6466. App.log.debug("Checking for updates @ %s" % full_url)
  6467. ### Get the data
  6468. try:
  6469. f = urllib.request.urlopen(full_url)
  6470. except:
  6471. # App.log.warning("Failed checking for latest version. Could not connect.")
  6472. self.log.warning("Failed checking for latest version. Could not connect.")
  6473. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6474. return
  6475. try:
  6476. data = json.load(f)
  6477. except Exception as e:
  6478. App.log.error("Could not parse information about latest version.")
  6479. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6480. App.log.debug("json.load(): %s" % str(e))
  6481. f.close()
  6482. return
  6483. f.close()
  6484. ### Latest version?
  6485. if self.version >= data["version"]:
  6486. App.log.debug("FlatCAM is up to date!")
  6487. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6488. return
  6489. App.log.debug("Newer version available.")
  6490. self.message.emit(
  6491. _("Newer Version Available"),
  6492. _("There is a newer version of FlatCAM available for download:\n\n") +
  6493. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6494. _("info")
  6495. )
  6496. def on_zoom_fit(self, event):
  6497. """
  6498. Callback for zoom-out request. This can be either from the corresponding
  6499. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6500. with axes limits from the geometry bounds of all objects.
  6501. :param event: Ignored.
  6502. :return: None
  6503. """
  6504. self.plotcanvas.fit_view()
  6505. def disable_all_plots(self):
  6506. self.report_usage("disable_all_plots()")
  6507. self.disable_plots(self.collection.get_list())
  6508. self.inform.emit(_("[success] All plots disabled."))
  6509. def disable_other_plots(self):
  6510. self.report_usage("disable_other_plots()")
  6511. self.disable_plots(self.collection.get_non_selected())
  6512. self.inform.emit(_("[success] All non selected plots disabled."))
  6513. def enable_all_plots(self):
  6514. self.report_usage("enable_all_plots()")
  6515. self.enable_plots(self.collection.get_list())
  6516. self.inform.emit(_("[success] All plots enabled."))
  6517. # TODO: FIX THIS
  6518. '''
  6519. By default this is not threaded
  6520. If threaded the app give warnings like this:
  6521. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6522. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6523. '''
  6524. def enable_plots(self, objects, threaded=False):
  6525. if threaded is True:
  6526. def worker_task(app_obj):
  6527. percentage = 0.1
  6528. try:
  6529. delta = 0.9 / len(objects)
  6530. except ZeroDivisionError:
  6531. self.progress.emit(0)
  6532. return
  6533. for obj in objects:
  6534. obj.options['plot'] = True
  6535. percentage += delta
  6536. self.progress.emit(int(percentage*100))
  6537. self.progress.emit(0)
  6538. self.plots_updated.emit()
  6539. self.collection.update_view()
  6540. # Send to worker
  6541. # self.worker.add_task(worker_task, [self])
  6542. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6543. else:
  6544. for obj in objects:
  6545. obj.options['plot'] = True
  6546. self.progress.emit(0)
  6547. self.plots_updated.emit()
  6548. self.collection.update_view()
  6549. # TODO: FIX THIS
  6550. '''
  6551. By default this is not threaded
  6552. If threaded the app give warnings like this:
  6553. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6554. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6555. '''
  6556. def disable_plots(self, objects, threaded=False):
  6557. # TODO: This method is very similar to replot_all. Try to merge.
  6558. """
  6559. Disables plots
  6560. :param objects: list
  6561. Objects to be disabled
  6562. :return:
  6563. """
  6564. if threaded is True:
  6565. self.progress.emit(10)
  6566. def worker_task(app_obj):
  6567. percentage = 0.1
  6568. try:
  6569. delta = 0.9 / len(objects)
  6570. except ZeroDivisionError:
  6571. self.progress.emit(0)
  6572. return
  6573. for obj in objects:
  6574. obj.options['plot'] = False
  6575. percentage += delta
  6576. self.progress.emit(int(percentage*100))
  6577. self.progress.emit(0)
  6578. self.plots_updated.emit()
  6579. self.collection.update_view()
  6580. # Send to worker
  6581. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6582. else:
  6583. for obj in objects:
  6584. obj.options['plot'] = False
  6585. self.plots_updated.emit()
  6586. self.collection.update_view()
  6587. def clear_plots(self):
  6588. objects = self.collection.get_list()
  6589. for obj in objects:
  6590. obj.clear(obj == objects[-1])
  6591. # Clear pool to free memory
  6592. self.clear_pool()
  6593. def generate_cnc_job(self, objects):
  6594. self.report_usage("generate_cnc_job()")
  6595. # for obj in objects:
  6596. # obj.generatecncjob()
  6597. for obj in objects:
  6598. obj.on_generatecnc_button_click()
  6599. def save_project(self, filename, quit=False):
  6600. """
  6601. Saves the current project to the specified file.
  6602. :param filename: Name of the file in which to save.
  6603. :type filename: str
  6604. :return: None
  6605. """
  6606. self.log.debug("save_project()")
  6607. self.save_in_progress = True
  6608. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6609. ## Capture the latest changes
  6610. # Current object
  6611. try:
  6612. self.collection.get_active().read_form()
  6613. except:
  6614. self.log.debug("There was no active object")
  6615. pass
  6616. # Project options
  6617. self.options_read_form()
  6618. # Serialize the whole project
  6619. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6620. "options": self.options,
  6621. "version": self.version}
  6622. if self.defaults["global_save_compressed"] is True:
  6623. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6624. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6625. # # Write
  6626. f.write(g)
  6627. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6628. else:
  6629. # Open file
  6630. try:
  6631. f = open(filename, 'w')
  6632. except IOError:
  6633. App.log.error("Failed to open file for saving: %s", filename)
  6634. return
  6635. # Write
  6636. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6637. f.close()
  6638. # verification of the saved project
  6639. # Open and parse
  6640. try:
  6641. saved_f = open(filename, 'r')
  6642. except IOError:
  6643. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6644. return
  6645. try:
  6646. saved_d = json.load(saved_f, object_hook=dict2obj)
  6647. except:
  6648. self.inform.emit(
  6649. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6650. f.close()
  6651. return
  6652. saved_f.close()
  6653. if 'version' in saved_d:
  6654. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6655. else:
  6656. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6657. # if quit:
  6658. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  6659. # t.start()
  6660. self.start_delayed_quit(delay=500, filename=filename, quit=quit)
  6661. def start_delayed_quit(self, delay, filename, quit=None):
  6662. """
  6663. :param delay: period of checking if project file size is more than zero; in seconds
  6664. :param filename: the name of the project file to be checked periodically for size more than zero
  6665. :return:
  6666. """
  6667. to_quit = quit
  6668. self.save_timer = QtCore.QTimer()
  6669. self.save_timer.setInterval(delay)
  6670. self.save_timer.timeout.connect(lambda : self.check_project_file_size(filename=filename, quit=to_quit))
  6671. self.save_timer.start()
  6672. def check_project_file_size(self, filename, quit=None):
  6673. """
  6674. :param filename: the name of the project file to be checked periodically for size more than zero
  6675. :return:
  6676. """
  6677. try:
  6678. if os.stat(filename).st_size > 0:
  6679. self.save_in_progress = False
  6680. self.save_timer.stop()
  6681. if quit:
  6682. self.app_quit.emit()
  6683. except Exception:
  6684. traceback.print_exc()
  6685. def on_options_app2project(self):
  6686. """
  6687. Callback for Options->Transfer Options->App=>Project. Copies options
  6688. from application defaults to project defaults.
  6689. :return: None
  6690. """
  6691. self.report_usage("on_options_app2project")
  6692. self.defaults_read_form()
  6693. self.options.update(self.defaults)
  6694. self.options_write_form()
  6695. def on_options_project2app(self):
  6696. """
  6697. Callback for Options->Transfer Options->Project=>App. Copies options
  6698. from project defaults to application defaults.
  6699. :return: None
  6700. """
  6701. self.report_usage("on_options_project2app")
  6702. self.options_read_form()
  6703. self.defaults.update(self.options)
  6704. self.defaults_write_form()
  6705. def on_options_project2object(self):
  6706. """
  6707. Callback for Options->Transfer Options->Project=>Object. Copies options
  6708. from project defaults to the currently selected object.
  6709. :return: None
  6710. """
  6711. self.report_usage("on_options_project2object")
  6712. self.options_read_form()
  6713. obj = self.collection.get_active()
  6714. if obj is None:
  6715. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6716. return
  6717. for option in self.options:
  6718. if option.find(obj.kind + "_") == 0:
  6719. oname = option[len(obj.kind) + 1:]
  6720. obj.options[oname] = self.options[option]
  6721. obj.to_form() # Update UI
  6722. def on_options_object2project(self):
  6723. """
  6724. Callback for Options->Transfer Options->Object=>Project. Copies options
  6725. from the currently selected object to project defaults.
  6726. :return: None
  6727. """
  6728. self.report_usage("on_options_object2project")
  6729. obj = self.collection.get_active()
  6730. if obj is None:
  6731. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6732. return
  6733. obj.read_form()
  6734. for option in obj.options:
  6735. if option in ['name']: # TODO: Handle this better...
  6736. continue
  6737. self.options[obj.kind + "_" + option] = obj.options[option]
  6738. self.options_write_form()
  6739. def on_options_object2app(self):
  6740. """
  6741. Callback for Options->Transfer Options->Object=>App. Copies options
  6742. from the currently selected object to application defaults.
  6743. :return: None
  6744. """
  6745. self.report_usage("on_options_object2app")
  6746. obj = self.collection.get_active()
  6747. if obj is None:
  6748. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6749. return
  6750. obj.read_form()
  6751. for option in obj.options:
  6752. if option in ['name']: # TODO: Handle this better...
  6753. continue
  6754. self.defaults[obj.kind + "_" + option] = obj.options[option]
  6755. self.defaults_write_form()
  6756. def on_options_app2object(self):
  6757. """
  6758. Callback for Options->Transfer Options->App=>Object. Copies options
  6759. from application defaults to the currently selected object.
  6760. :return: None
  6761. """
  6762. self.report_usage("on_options_app2object")
  6763. self.defaults_read_form()
  6764. obj = self.collection.get_active()
  6765. if obj is None:
  6766. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6767. return
  6768. for option in self.defaults:
  6769. if option.find(obj.kind + "_") == 0:
  6770. oname = option[len(obj.kind) + 1:]
  6771. obj.options[oname] = self.defaults[option]
  6772. obj.to_form() # Update UI
  6773. # end of file